babylon.no-module.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333
  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. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "key", {
  240. /**
  241. * Unique key for this effect
  242. */
  243. get: function () {
  244. return this._key;
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. /**
  250. * If the effect has been compiled and prepared.
  251. * @returns if the effect is compiled and prepared.
  252. */
  253. Effect.prototype.isReady = function () {
  254. return this._isReady;
  255. };
  256. /**
  257. * The engine the effect was initialized with.
  258. * @returns the engine.
  259. */
  260. Effect.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. /**
  264. * The compiled webGL program for the effect
  265. * @returns the webGL program.
  266. */
  267. Effect.prototype.getProgram = function () {
  268. return this._program;
  269. };
  270. /**
  271. * The set of names of attribute variables for the shader.
  272. * @returns An array of attribute names.
  273. */
  274. Effect.prototype.getAttributesNames = function () {
  275. return this._attributesNames;
  276. };
  277. /**
  278. * Returns the attribute at the given index.
  279. * @param index The index of the attribute.
  280. * @returns The location of the attribute.
  281. */
  282. Effect.prototype.getAttributeLocation = function (index) {
  283. return this._attributes[index];
  284. };
  285. /**
  286. * Returns the attribute based on the name of the variable.
  287. * @param name of the attribute to look up.
  288. * @returns the attribute location.
  289. */
  290. Effect.prototype.getAttributeLocationByName = function (name) {
  291. var index = this._attributesNames.indexOf(name);
  292. return this._attributes[index];
  293. };
  294. /**
  295. * The number of attributes.
  296. * @returns the numnber of attributes.
  297. */
  298. Effect.prototype.getAttributesCount = function () {
  299. return this._attributes.length;
  300. };
  301. /**
  302. * Gets the index of a uniform variable.
  303. * @param uniformName of the uniform to look up.
  304. * @returns the index.
  305. */
  306. Effect.prototype.getUniformIndex = function (uniformName) {
  307. return this._uniformsNames.indexOf(uniformName);
  308. };
  309. /**
  310. * Returns the attribute based on the name of the variable.
  311. * @param uniformName of the uniform to look up.
  312. * @returns the location of the uniform.
  313. */
  314. Effect.prototype.getUniform = function (uniformName) {
  315. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  316. };
  317. /**
  318. * Returns an array of sampler variable names
  319. * @returns The array of sampler variable neames.
  320. */
  321. Effect.prototype.getSamplers = function () {
  322. return this._samplers;
  323. };
  324. /**
  325. * The error from the last compilation.
  326. * @returns the error string.
  327. */
  328. Effect.prototype.getCompilationError = function () {
  329. return this._compilationError;
  330. };
  331. /**
  332. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  333. * @param func The callback to be used.
  334. */
  335. Effect.prototype.executeWhenCompiled = function (func) {
  336. if (this.isReady()) {
  337. func(this);
  338. return;
  339. }
  340. this.onCompileObservable.add(function (effect) {
  341. func(effect);
  342. });
  343. };
  344. /** @hidden */
  345. Effect.prototype._loadVertexShader = function (vertex, callback) {
  346. if (BABYLON.Tools.IsWindowObjectExist()) {
  347. // DOM element ?
  348. if (vertex instanceof HTMLElement) {
  349. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  350. callback(vertexCode);
  351. return;
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. callback(vertexBinary);
  358. return;
  359. }
  360. // Is in local store ?
  361. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  362. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  363. return;
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. callback(fragmentCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (fragment.substr(0, 7) === "base64:") {
  387. var fragmentBinary = window.atob(fragment.substr(7));
  388. callback(fragmentBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  393. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  394. return;
  395. }
  396. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  397. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  398. return;
  399. }
  400. var fragmentShaderUrl;
  401. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  402. fragmentShaderUrl = fragment;
  403. }
  404. else {
  405. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  406. }
  407. // Fragment shader
  408. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  409. };
  410. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  411. // Rebuild shaders source code
  412. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  413. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  414. vertexCode = prefix + vertexCode;
  415. fragmentCode = prefix + fragmentCode;
  416. // Number lines of shaders source code
  417. var i = 2;
  418. var regex = /\n/gm;
  419. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  420. i = 2;
  421. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  422. // Dump shaders name and formatted source code
  423. if (this.name.vertexElement) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  426. }
  427. else if (this.name.vertex) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  430. }
  431. else {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  434. }
  435. };
  436. ;
  437. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  438. var preparedSourceCode = this._processPrecision(sourceCode);
  439. if (this._engine.webGLVersion == 1) {
  440. callback(preparedSourceCode);
  441. return;
  442. }
  443. // Already converted
  444. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  445. callback(preparedSourceCode.replace("#version 300 es", ""));
  446. return;
  447. }
  448. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  449. // Remove extensions
  450. // #extension GL_OES_standard_derivatives : enable
  451. // #extension GL_EXT_shader_texture_lod : enable
  452. // #extension GL_EXT_frag_depth : enable
  453. // #extension GL_EXT_draw_buffers : require
  454. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  455. var result = preparedSourceCode.replace(regex, "");
  456. // Migrate to GLSL v300
  457. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  458. result = result.replace(/attribute[ \t]/g, "in ");
  459. result = result.replace(/[ \t]attribute/g, " in");
  460. if (isFragment) {
  461. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  462. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/texture2D\s*\(/g, "texture(");
  464. result = result.replace(/textureCube\s*\(/g, "texture(");
  465. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  466. result = result.replace(/gl_FragColor/g, "glFragColor");
  467. result = result.replace(/gl_FragData/g, "glFragData");
  468. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  469. }
  470. callback(result);
  471. };
  472. Effect.prototype._processIncludes = function (sourceCode, callback) {
  473. var _this = this;
  474. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  475. var match = regex.exec(sourceCode);
  476. var returnValue = new String(sourceCode);
  477. while (match != null) {
  478. var includeFile = match[1];
  479. // Uniform declaration
  480. if (includeFile.indexOf("__decl__") !== -1) {
  481. includeFile = includeFile.replace(/__decl__/, "");
  482. if (this._engine.supportsUniformBuffers) {
  483. includeFile = includeFile.replace(/Vertex/, "Ubo");
  484. includeFile = includeFile.replace(/Fragment/, "Ubo");
  485. }
  486. includeFile = includeFile + "Declaration";
  487. }
  488. if (Effect.IncludesShadersStore[includeFile]) {
  489. // Substitution
  490. var includeContent = Effect.IncludesShadersStore[includeFile];
  491. if (match[2]) {
  492. var splits = match[3].split(",");
  493. for (var index = 0; index < splits.length; index += 2) {
  494. var source = new RegExp(splits[index], "g");
  495. var dest = splits[index + 1];
  496. includeContent = includeContent.replace(source, dest);
  497. }
  498. }
  499. if (match[4]) {
  500. var indexString = match[5];
  501. if (indexString.indexOf("..") !== -1) {
  502. var indexSplits = indexString.split("..");
  503. var minIndex = parseInt(indexSplits[0]);
  504. var maxIndex = parseInt(indexSplits[1]);
  505. var sourceIncludeContent = includeContent.slice(0);
  506. includeContent = "";
  507. if (isNaN(maxIndex)) {
  508. maxIndex = this._indexParameters[indexSplits[1]];
  509. }
  510. for (var i = minIndex; i < maxIndex; i++) {
  511. if (!this._engine.supportsUniformBuffers) {
  512. // Ubo replacement
  513. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  514. return p1 + "{X}";
  515. });
  516. }
  517. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  518. }
  519. }
  520. else {
  521. if (!this._engine.supportsUniformBuffers) {
  522. // Ubo replacement
  523. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  524. return p1 + "{X}";
  525. });
  526. }
  527. includeContent = includeContent.replace(/\{X\}/g, indexString);
  528. }
  529. }
  530. // Replace
  531. returnValue = returnValue.replace(match[0], includeContent);
  532. }
  533. else {
  534. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  535. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  536. Effect.IncludesShadersStore[includeFile] = fileContent;
  537. _this._processIncludes(returnValue, callback);
  538. });
  539. return;
  540. }
  541. match = regex.exec(sourceCode);
  542. }
  543. callback(returnValue);
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else { // Sorry we did everything we can
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  714. * @param channel Name of the sampler variable.
  715. * @param texture Texture to set.
  716. */
  717. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  718. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  719. };
  720. /**
  721. * Sets an array of textures on the engine to be used in the shader.
  722. * @param channel Name of the variable.
  723. * @param textures Textures to set.
  724. */
  725. Effect.prototype.setTextureArray = function (channel, textures) {
  726. if (this._samplers.indexOf(channel + "Ex") === -1) {
  727. var initialPos = this._samplers.indexOf(channel);
  728. for (var index = 1; index < textures.length; index++) {
  729. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  730. }
  731. }
  732. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  733. };
  734. /**
  735. * 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)
  736. * @param channel Name of the sampler variable.
  737. * @param postProcess Post process to get the input texture from.
  738. */
  739. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  740. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  741. };
  742. /**
  743. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  744. * 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)
  745. * @param channel Name of the sampler variable.
  746. * @param postProcess Post process to get the output texture from.
  747. */
  748. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  749. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  750. };
  751. /** @hidden */
  752. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  753. var cache = this._valueCache[uniformName];
  754. var flag = matrix.updateFlag;
  755. if (cache !== undefined && cache === flag) {
  756. return false;
  757. }
  758. this._valueCache[uniformName] = flag;
  759. return true;
  760. };
  761. /** @hidden */
  762. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. return changed;
  779. };
  780. /** @hidden */
  781. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  782. var cache = this._valueCache[uniformName];
  783. if (!cache) {
  784. cache = [x, y, z];
  785. this._valueCache[uniformName] = cache;
  786. return true;
  787. }
  788. var changed = false;
  789. if (cache[0] !== x) {
  790. cache[0] = x;
  791. changed = true;
  792. }
  793. if (cache[1] !== y) {
  794. cache[1] = y;
  795. changed = true;
  796. }
  797. if (cache[2] !== z) {
  798. cache[2] = z;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z, w];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. if (cache[3] !== w) {
  825. cache[3] = w;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /**
  831. * Binds a buffer to a uniform.
  832. * @param buffer Buffer to bind.
  833. * @param name Name of the uniform variable to bind to.
  834. */
  835. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  836. var bufferName = this._uniformBuffersNames[name];
  837. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  838. return;
  839. }
  840. Effect._baseCache[bufferName] = buffer;
  841. this._engine.bindUniformBufferBase(buffer, bufferName);
  842. };
  843. /**
  844. * Binds block to a uniform.
  845. * @param blockName Name of the block to bind.
  846. * @param index Index to bind.
  847. */
  848. Effect.prototype.bindUniformBlock = function (blockName, index) {
  849. this._engine.bindUniformBlock(this._program, blockName, index);
  850. };
  851. /**
  852. * Sets an interger value on a uniform variable.
  853. * @param uniformName Name of the variable.
  854. * @param value Value to be set.
  855. * @returns this effect.
  856. */
  857. Effect.prototype.setInt = function (uniformName, value) {
  858. var cache = this._valueCache[uniformName];
  859. if (cache !== undefined && cache === value)
  860. return this;
  861. this._valueCache[uniformName] = value;
  862. this._engine.setInt(this.getUniform(uniformName), value);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * 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)
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setIntArray2 = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setIntArray2(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setIntArray3 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setIntArray3(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setIntArray4 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setIntArray4(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * 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)
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * 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)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * 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)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets matrices on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param matrices matrices to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1004. if (!matrices) {
  1005. return this;
  1006. }
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets matrix on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param matrix matrix to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1018. if (this._cacheMatrix(uniformName, matrix)) {
  1019. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1020. }
  1021. return this;
  1022. };
  1023. /**
  1024. * 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)
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1041. this._valueCache[uniformName] = null;
  1042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1043. return this;
  1044. };
  1045. /**
  1046. * Sets a float on a uniform variable.
  1047. * @param uniformName Name of the variable.
  1048. * @param value value to be set.
  1049. * @returns this effect.
  1050. */
  1051. Effect.prototype.setFloat = function (uniformName, value) {
  1052. var cache = this._valueCache[uniformName];
  1053. if (cache !== undefined && cache === value)
  1054. return this;
  1055. this._valueCache[uniformName] = value;
  1056. this._engine.setFloat(this.getUniform(uniformName), value);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a boolean on a uniform variable.
  1061. * @param uniformName Name of the variable.
  1062. * @param bool value to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setBool = function (uniformName, bool) {
  1066. var cache = this._valueCache[uniformName];
  1067. if (cache !== undefined && cache === bool)
  1068. return this;
  1069. this._valueCache[uniformName] = bool;
  1070. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a Vector2 on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param vector2 vector2 to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1080. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1081. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1082. }
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param x First float in float2.
  1089. * @param y Second float in float2.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1093. if (this._cacheFloat2(uniformName, x, y)) {
  1094. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1095. }
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector3 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector3 Value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1105. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1106. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float3.
  1114. * @param y Second float in float3.
  1115. * @param z Third float in float3.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1119. if (this._cacheFloat3(uniformName, x, y, z)) {
  1120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a Vector4 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param vector4 Value to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1131. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1132. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a float4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param x First float in float4.
  1140. * @param y Second float in float4.
  1141. * @param z Third float in float4.
  1142. * @param w Fourth float in float4.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1146. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Color3 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param color3 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setColor3 = function (uniformName, color3) {
  1158. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1159. this._engine.setColor3(this.getUniform(uniformName), color3);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @param alpha Alpha value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1171. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1172. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color4 on a uniform variable
  1178. * @param uniformName defines the name of the variable
  1179. * @param color4 defines the value to be set
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1183. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1184. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Resets the cache of effects.
  1190. */
  1191. Effect.ResetCache = function () {
  1192. Effect._baseCache = {};
  1193. };
  1194. Effect._uniqueIdSeed = 0;
  1195. Effect._baseCache = {};
  1196. /**
  1197. * Store of each shader (The can be looked up using effect.key)
  1198. */
  1199. Effect.ShadersStore = {};
  1200. /**
  1201. * Store of each included file for a shader (The can be looked up using effect.key)
  1202. */
  1203. Effect.IncludesShadersStore = {};
  1204. return Effect;
  1205. }());
  1206. BABYLON.Effect = Effect;
  1207. })(BABYLON || (BABYLON = {}));
  1208. //# sourceMappingURL=babylon.effect.js.map
  1209. //# sourceMappingURL=babylon.types.js.map
  1210. var BABYLON;
  1211. (function (BABYLON) {
  1212. var KeyboardEventTypes = /** @class */ (function () {
  1213. function KeyboardEventTypes() {
  1214. }
  1215. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1216. get: function () {
  1217. return KeyboardEventTypes._KEYDOWN;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1223. get: function () {
  1224. return KeyboardEventTypes._KEYUP;
  1225. },
  1226. enumerable: true,
  1227. configurable: true
  1228. });
  1229. KeyboardEventTypes._KEYDOWN = 0x01;
  1230. KeyboardEventTypes._KEYUP = 0x02;
  1231. return KeyboardEventTypes;
  1232. }());
  1233. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1234. var KeyboardInfo = /** @class */ (function () {
  1235. function KeyboardInfo(type, event) {
  1236. this.type = type;
  1237. this.event = event;
  1238. }
  1239. return KeyboardInfo;
  1240. }());
  1241. BABYLON.KeyboardInfo = KeyboardInfo;
  1242. /**
  1243. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1244. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1245. */
  1246. var KeyboardInfoPre = /** @class */ (function (_super) {
  1247. __extends(KeyboardInfoPre, _super);
  1248. function KeyboardInfoPre(type, event) {
  1249. var _this = _super.call(this, type, event) || this;
  1250. _this.skipOnPointerObservable = false;
  1251. return _this;
  1252. }
  1253. return KeyboardInfoPre;
  1254. }(KeyboardInfo));
  1255. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1256. })(BABYLON || (BABYLON = {}));
  1257. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1258. var BABYLON;
  1259. (function (BABYLON) {
  1260. var PointerEventTypes = /** @class */ (function () {
  1261. function PointerEventTypes() {
  1262. }
  1263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERDOWN;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERUP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERMOVE;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERWHEEL;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERPICK;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1299. get: function () {
  1300. return PointerEventTypes._POINTERTAP;
  1301. },
  1302. enumerable: true,
  1303. configurable: true
  1304. });
  1305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1306. get: function () {
  1307. return PointerEventTypes._POINTERDOUBLETAP;
  1308. },
  1309. enumerable: true,
  1310. configurable: true
  1311. });
  1312. PointerEventTypes._POINTERDOWN = 0x01;
  1313. PointerEventTypes._POINTERUP = 0x02;
  1314. PointerEventTypes._POINTERMOVE = 0x04;
  1315. PointerEventTypes._POINTERWHEEL = 0x08;
  1316. PointerEventTypes._POINTERPICK = 0x10;
  1317. PointerEventTypes._POINTERTAP = 0x20;
  1318. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1319. return PointerEventTypes;
  1320. }());
  1321. BABYLON.PointerEventTypes = PointerEventTypes;
  1322. var PointerInfoBase = /** @class */ (function () {
  1323. function PointerInfoBase(type, event) {
  1324. this.type = type;
  1325. this.event = event;
  1326. }
  1327. return PointerInfoBase;
  1328. }());
  1329. BABYLON.PointerInfoBase = PointerInfoBase;
  1330. /**
  1331. * This class is used to store pointer related info for the onPrePointerObservable event.
  1332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1333. */
  1334. var PointerInfoPre = /** @class */ (function (_super) {
  1335. __extends(PointerInfoPre, _super);
  1336. function PointerInfoPre(type, event, localX, localY) {
  1337. var _this = _super.call(this, type, event) || this;
  1338. _this.skipOnPointerObservable = false;
  1339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1340. return _this;
  1341. }
  1342. return PointerInfoPre;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfoPre = PointerInfoPre;
  1345. /**
  1346. * This type contains all the data related to a pointer event in Babylon.js.
  1347. * 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.
  1348. */
  1349. var PointerInfo = /** @class */ (function (_super) {
  1350. __extends(PointerInfo, _super);
  1351. function PointerInfo(type, event, pickInfo) {
  1352. var _this = _super.call(this, type, event) || this;
  1353. _this.pickInfo = pickInfo;
  1354. return _this;
  1355. }
  1356. return PointerInfo;
  1357. }(PointerInfoBase));
  1358. BABYLON.PointerInfo = PointerInfo;
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.pointerEvents.js.map
  1361. var BABYLON;
  1362. (function (BABYLON) {
  1363. BABYLON.ToGammaSpace = 1 / 2.2;
  1364. BABYLON.ToLinearSpace = 2.2;
  1365. BABYLON.Epsilon = 0.001;
  1366. /**
  1367. * Class used to hold a RBG color
  1368. */
  1369. var Color3 = /** @class */ (function () {
  1370. /**
  1371. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1372. * @param r defines the red component (between 0 and 1, default is 0)
  1373. * @param g defines the green component (between 0 and 1, default is 0)
  1374. * @param b defines the blue component (between 0 and 1, default is 0)
  1375. */
  1376. function Color3(
  1377. /**
  1378. * Defines the red component (between 0 and 1, default is 0)
  1379. */
  1380. r,
  1381. /**
  1382. * Defines the green component (between 0 and 1, default is 0)
  1383. */
  1384. g,
  1385. /**
  1386. * Defines the blue component (between 0 and 1, default is 0)
  1387. */
  1388. b) {
  1389. if (r === void 0) { r = 0; }
  1390. if (g === void 0) { g = 0; }
  1391. if (b === void 0) { b = 0; }
  1392. this.r = r;
  1393. this.g = g;
  1394. this.b = b;
  1395. }
  1396. /**
  1397. * Creates a string with the Color3 current values
  1398. * @returns the string representation of the Color3 object
  1399. */
  1400. Color3.prototype.toString = function () {
  1401. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1402. };
  1403. /**
  1404. * Returns the string "Color3"
  1405. * @returns "Color3"
  1406. */
  1407. Color3.prototype.getClassName = function () {
  1408. return "Color3";
  1409. };
  1410. /**
  1411. * Compute the Color3 hash code
  1412. * @returns an unique number that can be used to hash Color3 objects
  1413. */
  1414. Color3.prototype.getHashCode = function () {
  1415. var hash = this.r || 0;
  1416. hash = (hash * 397) ^ (this.g || 0);
  1417. hash = (hash * 397) ^ (this.b || 0);
  1418. return hash;
  1419. };
  1420. // Operators
  1421. /**
  1422. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1423. * @param array defines the array where to store the r,g,b components
  1424. * @param index defines an optional index in the target array to define where to start storing values
  1425. * @returns the current Color3 object
  1426. */
  1427. Color3.prototype.toArray = function (array, index) {
  1428. if (index === undefined) {
  1429. index = 0;
  1430. }
  1431. array[index] = this.r;
  1432. array[index + 1] = this.g;
  1433. array[index + 2] = this.b;
  1434. return this;
  1435. };
  1436. /**
  1437. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1438. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1439. * @returns a new {BABYLON.Color4} object
  1440. */
  1441. Color3.prototype.toColor4 = function (alpha) {
  1442. if (alpha === void 0) { alpha = 1; }
  1443. return new Color4(this.r, this.g, this.b, alpha);
  1444. };
  1445. /**
  1446. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1447. * @returns the new array
  1448. */
  1449. Color3.prototype.asArray = function () {
  1450. var result = new Array();
  1451. this.toArray(result, 0);
  1452. return result;
  1453. };
  1454. /**
  1455. * Returns the luminance value
  1456. * @returns a float value
  1457. */
  1458. Color3.prototype.toLuminance = function () {
  1459. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1460. };
  1461. /**
  1462. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1463. * @param otherColor defines the second operand
  1464. * @returns the new Color3 object
  1465. */
  1466. Color3.prototype.multiply = function (otherColor) {
  1467. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1468. };
  1469. /**
  1470. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1471. * @param otherColor defines the second operand
  1472. * @param result defines the Color3 object where to store the result
  1473. * @returns the current Color3
  1474. */
  1475. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1476. result.r = this.r * otherColor.r;
  1477. result.g = this.g * otherColor.g;
  1478. result.b = this.b * otherColor.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Determines equality between Color3 objects
  1483. * @param otherColor defines the second operand
  1484. * @returns true if the rgb values are equal to the given ones
  1485. */
  1486. Color3.prototype.equals = function (otherColor) {
  1487. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1488. };
  1489. /**
  1490. * Determines equality between the current Color3 object and a set of r,b,g values
  1491. * @param r defines the red component to check
  1492. * @param g defines the green component to check
  1493. * @param b defines the blue component to check
  1494. * @returns true if the rgb values are equal to the given ones
  1495. */
  1496. Color3.prototype.equalsFloats = function (r, g, b) {
  1497. return this.r === r && this.g === g && this.b === b;
  1498. };
  1499. /**
  1500. * Multiplies in place each rgb value by scale
  1501. * @param scale defines the scaling factor
  1502. * @returns the updated Color3
  1503. */
  1504. Color3.prototype.scale = function (scale) {
  1505. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1506. };
  1507. /**
  1508. * Multiplies the rgb values by scale and stores the result into "result"
  1509. * @param scale defines the scaling factor
  1510. * @param result defines the Color3 object where to store the result
  1511. * @returns the unmodified current Color3
  1512. */
  1513. Color3.prototype.scaleToRef = function (scale, result) {
  1514. result.r = this.r * scale;
  1515. result.g = this.g * scale;
  1516. result.b = this.b * scale;
  1517. return this;
  1518. };
  1519. /**
  1520. * Scale the current Color3 values by a factor and add the result to a given Color3
  1521. * @param scale defines the scale factor
  1522. * @param result defines color to store the result into
  1523. * @returns the unmodified current Color3
  1524. */
  1525. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1526. result.r += this.r * scale;
  1527. result.g += this.g * scale;
  1528. result.b += this.b * scale;
  1529. return this;
  1530. };
  1531. /**
  1532. * Clamps the rgb values by the min and max values and stores the result into "result"
  1533. * @param min defines minimum clamping value (default is 0)
  1534. * @param max defines maximum clamping value (default is 1)
  1535. * @param result defines color to store the result into
  1536. * @returns the original Color3
  1537. */
  1538. Color3.prototype.clampToRef = function (min, max, result) {
  1539. if (min === void 0) { min = 0; }
  1540. if (max === void 0) { max = 1; }
  1541. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1542. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1543. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1544. return this;
  1545. };
  1546. /**
  1547. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1548. * @param otherColor defines the second operand
  1549. * @returns the new Color3
  1550. */
  1551. Color3.prototype.add = function (otherColor) {
  1552. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1553. };
  1554. /**
  1555. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1556. * @param otherColor defines the second operand
  1557. * @param result defines Color3 object to store the result into
  1558. * @returns the unmodified current Color3
  1559. */
  1560. Color3.prototype.addToRef = function (otherColor, result) {
  1561. result.r = this.r + otherColor.r;
  1562. result.g = this.g + otherColor.g;
  1563. result.b = this.b + otherColor.b;
  1564. return this;
  1565. };
  1566. /**
  1567. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1568. * @param otherColor defines the second operand
  1569. * @returns the new Color3
  1570. */
  1571. Color3.prototype.subtract = function (otherColor) {
  1572. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1573. };
  1574. /**
  1575. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1576. * @param otherColor defines the second operand
  1577. * @param result defines Color3 object to store the result into
  1578. * @returns the unmodified current Color3
  1579. */
  1580. Color3.prototype.subtractToRef = function (otherColor, result) {
  1581. result.r = this.r - otherColor.r;
  1582. result.g = this.g - otherColor.g;
  1583. result.b = this.b - otherColor.b;
  1584. return this;
  1585. };
  1586. /**
  1587. * Copy the current object
  1588. * @returns a new Color3 copied the current one
  1589. */
  1590. Color3.prototype.clone = function () {
  1591. return new Color3(this.r, this.g, this.b);
  1592. };
  1593. /**
  1594. * Copies the rgb values from the source in the current Color3
  1595. * @param source defines the source Color3 object
  1596. * @returns the updated Color3 object
  1597. */
  1598. Color3.prototype.copyFrom = function (source) {
  1599. this.r = source.r;
  1600. this.g = source.g;
  1601. this.b = source.b;
  1602. return this;
  1603. };
  1604. /**
  1605. * Updates the Color3 rgb values from the given floats
  1606. * @param r defines the red component to read from
  1607. * @param g defines the green component to read from
  1608. * @param b defines the blue component to read from
  1609. * @returns the current Color3 object
  1610. */
  1611. Color3.prototype.copyFromFloats = function (r, g, b) {
  1612. this.r = r;
  1613. this.g = g;
  1614. this.b = b;
  1615. return this;
  1616. };
  1617. /**
  1618. * Updates the Color3 rgb values from the given floats
  1619. * @param r defines the red component to read from
  1620. * @param g defines the green component to read from
  1621. * @param b defines the blue component to read from
  1622. * @returns the current Color3 object
  1623. */
  1624. Color3.prototype.set = function (r, g, b) {
  1625. return this.copyFromFloats(r, g, b);
  1626. };
  1627. /**
  1628. * Compute the Color3 hexadecimal code as a string
  1629. * @returns a string containing the hexadecimal representation of the Color3 object
  1630. */
  1631. Color3.prototype.toHexString = function () {
  1632. var intR = (this.r * 255) | 0;
  1633. var intG = (this.g * 255) | 0;
  1634. var intB = (this.b * 255) | 0;
  1635. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1636. };
  1637. /**
  1638. * Computes a new Color3 converted from the current one to linear space
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.prototype.toLinearSpace = function () {
  1642. var convertedColor = new Color3();
  1643. this.toLinearSpaceToRef(convertedColor);
  1644. return convertedColor;
  1645. };
  1646. /**
  1647. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1648. * @param convertedColor defines the Color3 object where to store the linear space version
  1649. * @returns the unmodified Color3
  1650. */
  1651. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1652. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1653. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1654. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1655. return this;
  1656. };
  1657. /**
  1658. * Computes a new Color3 converted from the current one to gamma space
  1659. * @returns a new Color3 object
  1660. */
  1661. Color3.prototype.toGammaSpace = function () {
  1662. var convertedColor = new Color3();
  1663. this.toGammaSpaceToRef(convertedColor);
  1664. return convertedColor;
  1665. };
  1666. /**
  1667. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1668. * @param convertedColor defines the Color3 object where to store the gamma space version
  1669. * @returns the unmodified Color3
  1670. */
  1671. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1672. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1673. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1674. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1675. return this;
  1676. };
  1677. // Statics
  1678. /**
  1679. * Creates a new Color3 from the string containing valid hexadecimal values
  1680. * @param hex defines a string containing valid hexadecimal values
  1681. * @returns a new Color3 object
  1682. */
  1683. Color3.FromHexString = function (hex) {
  1684. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1685. return new Color3(0, 0, 0);
  1686. }
  1687. var r = parseInt(hex.substring(1, 3), 16);
  1688. var g = parseInt(hex.substring(3, 5), 16);
  1689. var b = parseInt(hex.substring(5, 7), 16);
  1690. return Color3.FromInts(r, g, b);
  1691. };
  1692. /**
  1693. * Creates a new Vector3 from the starting index of the given array
  1694. * @param array defines the source array
  1695. * @param offset defines an offset in the source array
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromArray = function (array, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1701. };
  1702. /**
  1703. * Creates a new Color3 from integer values (< 256)
  1704. * @param r defines the red component to read from (value between 0 and 255)
  1705. * @param g defines the green component to read from (value between 0 and 255)
  1706. * @param b defines the blue component to read from (value between 0 and 255)
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.FromInts = function (r, g, b) {
  1710. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1711. };
  1712. /**
  1713. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1714. * @param start defines the start Color3 value
  1715. * @param end defines the end Color3 value
  1716. * @param amount defines the gradient value between start and end
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Lerp = function (start, end, amount) {
  1720. var r = start.r + ((end.r - start.r) * amount);
  1721. var g = start.g + ((end.g - start.g) * amount);
  1722. var b = start.b + ((end.b - start.b) * amount);
  1723. return new Color3(r, g, b);
  1724. };
  1725. /**
  1726. * Returns a Color3 value containing a red color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Red = function () { return new Color3(1, 0, 0); };
  1730. /**
  1731. * Returns a Color3 value containing a green color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Green = function () { return new Color3(0, 1, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a blue color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1740. /**
  1741. * Returns a Color3 value containing a black color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Black = function () { return new Color3(0, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a white color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.White = function () { return new Color3(1, 1, 1); };
  1750. /**
  1751. * Returns a Color3 value containing a purple color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1755. /**
  1756. * Returns a Color3 value containing a magenta color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1760. /**
  1761. * Returns a Color3 value containing a yellow color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a gray color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a teal color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1775. /**
  1776. * Returns a Color3 value containing a random color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1780. return Color3;
  1781. }());
  1782. BABYLON.Color3 = Color3;
  1783. /**
  1784. * Class used to hold a RBGA color
  1785. */
  1786. var Color4 = /** @class */ (function () {
  1787. /**
  1788. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1789. * @param r defines the red component (between 0 and 1, default is 0)
  1790. * @param g defines the green component (between 0 and 1, default is 0)
  1791. * @param b defines the blue component (between 0 and 1, default is 0)
  1792. * @param a defines the alpha component (between 0 and 1, default is 1)
  1793. */
  1794. function Color4(
  1795. /**
  1796. * Defines the red component (between 0 and 1, default is 0)
  1797. */
  1798. r,
  1799. /**
  1800. * Defines the green component (between 0 and 1, default is 0)
  1801. */
  1802. g,
  1803. /**
  1804. * Defines the blue component (between 0 and 1, default is 0)
  1805. */
  1806. b,
  1807. /**
  1808. * Defines the alpha component (between 0 and 1, default is 1)
  1809. */
  1810. a) {
  1811. if (r === void 0) { r = 0; }
  1812. if (g === void 0) { g = 0; }
  1813. if (b === void 0) { b = 0; }
  1814. if (a === void 0) { a = 1; }
  1815. this.r = r;
  1816. this.g = g;
  1817. this.b = b;
  1818. this.a = a;
  1819. }
  1820. // Operators
  1821. /**
  1822. * Adds in place the given Color4 values to the current Color4 object
  1823. * @param right defines the second operand
  1824. * @returns the current updated Color4 object
  1825. */
  1826. Color4.prototype.addInPlace = function (right) {
  1827. this.r += right.r;
  1828. this.g += right.g;
  1829. this.b += right.b;
  1830. this.a += right.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1835. * @returns the new array
  1836. */
  1837. Color4.prototype.asArray = function () {
  1838. var result = new Array();
  1839. this.toArray(result, 0);
  1840. return result;
  1841. };
  1842. /**
  1843. * Stores from the starting index in the given array the Color4 successive values
  1844. * @param array defines the array where to store the r,g,b components
  1845. * @param index defines an optional index in the target array to define where to start storing values
  1846. * @returns the current Color4 object
  1847. */
  1848. Color4.prototype.toArray = function (array, index) {
  1849. if (index === undefined) {
  1850. index = 0;
  1851. }
  1852. array[index] = this.r;
  1853. array[index + 1] = this.g;
  1854. array[index + 2] = this.b;
  1855. array[index + 3] = this.a;
  1856. return this;
  1857. };
  1858. /**
  1859. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1860. * @param right defines the second operand
  1861. * @returns a new Color4 object
  1862. */
  1863. Color4.prototype.add = function (right) {
  1864. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1865. };
  1866. /**
  1867. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1868. * @param right defines the second operand
  1869. * @returns a new Color4 object
  1870. */
  1871. Color4.prototype.subtract = function (right) {
  1872. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1873. };
  1874. /**
  1875. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1876. * @param right defines the second operand
  1877. * @param result defines the Color4 object where to store the result
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.subtractToRef = function (right, result) {
  1881. result.r = this.r - right.r;
  1882. result.g = this.g - right.g;
  1883. result.b = this.b - right.b;
  1884. result.a = this.a - right.a;
  1885. return this;
  1886. };
  1887. /**
  1888. * Creates a new Color4 with the current Color4 values multiplied by scale
  1889. * @param scale defines the scaling factor to apply
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.scale = function (scale) {
  1893. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1894. };
  1895. /**
  1896. * Multiplies the current Color4 values by scale and stores the result in "result"
  1897. * @param scale defines the scaling factor to apply
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current unmodified Color4
  1900. */
  1901. Color4.prototype.scaleToRef = function (scale, result) {
  1902. result.r = this.r * scale;
  1903. result.g = this.g * scale;
  1904. result.b = this.b * scale;
  1905. result.a = this.a * scale;
  1906. return this;
  1907. };
  1908. /**
  1909. * Scale the current Color4 values by a factor and add the result to a given Color4
  1910. * @param scale defines the scale factor
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the unmodified current Color4
  1913. */
  1914. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1915. result.r += this.r * scale;
  1916. result.g += this.g * scale;
  1917. result.b += this.b * scale;
  1918. result.a += this.a * scale;
  1919. return this;
  1920. };
  1921. /**
  1922. * Clamps the rgb values by the min and max values and stores the result into "result"
  1923. * @param min defines minimum clamping value (default is 0)
  1924. * @param max defines maximum clamping value (default is 1)
  1925. * @param result defines color to store the result into.
  1926. * @returns the cuurent Color4
  1927. */
  1928. Color4.prototype.clampToRef = function (min, max, result) {
  1929. if (min === void 0) { min = 0; }
  1930. if (max === void 0) { max = 1; }
  1931. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1932. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1933. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1934. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1935. return this;
  1936. };
  1937. /**
  1938. * Multipy an Color4 value by another and return a new Color4 object
  1939. * @param color defines the Color4 value to multiply by
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.multiply = function (color) {
  1943. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1944. };
  1945. /**
  1946. * Multipy a Color4 value by another and push the result in a reference value
  1947. * @param color defines the Color4 value to multiply by
  1948. * @param result defines the Color4 to fill the result in
  1949. * @returns the result Color4
  1950. */
  1951. Color4.prototype.multiplyToRef = function (color, result) {
  1952. result.r = this.r * color.r;
  1953. result.g = this.g * color.g;
  1954. result.b = this.b * color.b;
  1955. result.a = this.a * color.a;
  1956. return result;
  1957. };
  1958. /**
  1959. * Creates a string with the Color4 current values
  1960. * @returns the string representation of the Color4 object
  1961. */
  1962. Color4.prototype.toString = function () {
  1963. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Color4"
  1967. * @returns "Color4"
  1968. */
  1969. Color4.prototype.getClassName = function () {
  1970. return "Color4";
  1971. };
  1972. /**
  1973. * Compute the Color4 hash code
  1974. * @returns an unique number that can be used to hash Color4 objects
  1975. */
  1976. Color4.prototype.getHashCode = function () {
  1977. var hash = this.r || 0;
  1978. hash = (hash * 397) ^ (this.g || 0);
  1979. hash = (hash * 397) ^ (this.b || 0);
  1980. hash = (hash * 397) ^ (this.a || 0);
  1981. return hash;
  1982. };
  1983. /**
  1984. * Creates a new Color4 copied from the current one
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.clone = function () {
  1988. return new Color4(this.r, this.g, this.b, this.a);
  1989. };
  1990. /**
  1991. * Copies the given Color4 values into the current one
  1992. * @param source defines the source Color4 object
  1993. * @returns the current updated Color4 object
  1994. */
  1995. Color4.prototype.copyFrom = function (source) {
  1996. this.r = source.r;
  1997. this.g = source.g;
  1998. this.b = source.b;
  1999. this.a = source.a;
  2000. return this;
  2001. };
  2002. /**
  2003. * Copies the given float values into the current one
  2004. * @param r defines the red component to read from
  2005. * @param g defines the green component to read from
  2006. * @param b defines the blue component to read from
  2007. * @param a defines the alpha component to read from
  2008. * @returns the current updated Color4 object
  2009. */
  2010. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2011. this.r = r;
  2012. this.g = g;
  2013. this.b = b;
  2014. this.a = a;
  2015. return this;
  2016. };
  2017. /**
  2018. * Copies the given float values into the current one
  2019. * @param r defines the red component to read from
  2020. * @param g defines the green component to read from
  2021. * @param b defines the blue component to read from
  2022. * @param a defines the alpha component to read from
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.set = function (r, g, b, a) {
  2026. return this.copyFromFloats(r, g, b, a);
  2027. };
  2028. /**
  2029. * Compute the Color4 hexadecimal code as a string
  2030. * @returns a string containing the hexadecimal representation of the Color4 object
  2031. */
  2032. Color4.prototype.toHexString = function () {
  2033. var intR = (this.r * 255) | 0;
  2034. var intG = (this.g * 255) | 0;
  2035. var intB = (this.b * 255) | 0;
  2036. var intA = (this.a * 255) | 0;
  2037. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2038. };
  2039. /**
  2040. * Computes a new Color4 converted from the current one to linear space
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.toLinearSpace = function () {
  2044. var convertedColor = new Color4();
  2045. this.toLinearSpaceToRef(convertedColor);
  2046. return convertedColor;
  2047. };
  2048. /**
  2049. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2050. * @param convertedColor defines the Color4 object where to store the linear space version
  2051. * @returns the unmodified Color4
  2052. */
  2053. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2054. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2055. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2056. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2057. convertedColor.a = this.a;
  2058. return this;
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to gamma space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toGammaSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toGammaSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the gamma space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. // Statics
  2082. /**
  2083. * Creates a new Color4 from the string containing valid hexadecimal values
  2084. * @param hex defines a string containing valid hexadecimal values
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromHexString = function (hex) {
  2088. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2089. return new Color4(0.0, 0.0, 0.0, 0.0);
  2090. }
  2091. var r = parseInt(hex.substring(1, 3), 16);
  2092. var g = parseInt(hex.substring(3, 5), 16);
  2093. var b = parseInt(hex.substring(5, 7), 16);
  2094. var a = parseInt(hex.substring(7, 9), 16);
  2095. return Color4.FromInts(r, g, b, a);
  2096. };
  2097. /**
  2098. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2099. * @param left defines the start value
  2100. * @param right defines the end value
  2101. * @param amount defines the gradient factor
  2102. * @returns a new Color4 object
  2103. */
  2104. Color4.Lerp = function (left, right, amount) {
  2105. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2106. Color4.LerpToRef(left, right, amount, result);
  2107. return result;
  2108. };
  2109. /**
  2110. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2111. * @param left defines the start value
  2112. * @param right defines the end value
  2113. * @param amount defines the gradient factor
  2114. * @param result defines the Color4 object where to store data
  2115. */
  2116. Color4.LerpToRef = function (left, right, amount, result) {
  2117. result.r = left.r + (right.r - left.r) * amount;
  2118. result.g = left.g + (right.g - left.g) * amount;
  2119. result.b = left.b + (right.b - left.b) * amount;
  2120. result.a = left.a + (right.a - left.a) * amount;
  2121. };
  2122. /**
  2123. * Creates a new Color4 from the starting index element of the given array
  2124. * @param array defines the source array to read from
  2125. * @param offset defines the offset in the source array
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.FromArray = function (array, offset) {
  2129. if (offset === void 0) { offset = 0; }
  2130. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2131. };
  2132. /**
  2133. * Creates a new Color3 from integer values (< 256)
  2134. * @param r defines the red component to read from (value between 0 and 255)
  2135. * @param g defines the green component to read from (value between 0 and 255)
  2136. * @param b defines the blue component to read from (value between 0 and 255)
  2137. * @param a defines the alpha component to read from (value between 0 and 255)
  2138. * @returns a new Color3 object
  2139. */
  2140. Color4.FromInts = function (r, g, b, a) {
  2141. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2142. };
  2143. /**
  2144. * Check the content of a given array and convert it to an array containing RGBA data
  2145. * If the original array was already containing count * 4 values then it is returned directly
  2146. * @param colors defines the array to check
  2147. * @param count defines the number of RGBA data to expect
  2148. * @returns an array containing count * 4 values (RGBA)
  2149. */
  2150. Color4.CheckColors4 = function (colors, count) {
  2151. // Check if color3 was used
  2152. if (colors.length === count * 3) {
  2153. var colors4 = [];
  2154. for (var index = 0; index < colors.length; index += 3) {
  2155. var newIndex = (index / 3) * 4;
  2156. colors4[newIndex] = colors[index];
  2157. colors4[newIndex + 1] = colors[index + 1];
  2158. colors4[newIndex + 2] = colors[index + 2];
  2159. colors4[newIndex + 3] = 1.0;
  2160. }
  2161. return colors4;
  2162. }
  2163. return colors;
  2164. };
  2165. return Color4;
  2166. }());
  2167. BABYLON.Color4 = Color4;
  2168. /**
  2169. * Class representing a vector containing 2 coordinates
  2170. */
  2171. var Vector2 = /** @class */ (function () {
  2172. /**
  2173. * Creates a new Vector2 from the given x and y coordinates
  2174. * @param x defines the first coordinate
  2175. * @param y defines the second coordinate
  2176. */
  2177. function Vector2(
  2178. /** defines the first coordinate */
  2179. x,
  2180. /** defines the second coordinate */
  2181. y) {
  2182. this.x = x;
  2183. this.y = y;
  2184. }
  2185. /**
  2186. * Gets a string with the Vector2 coordinates
  2187. * @returns a string with the Vector2 coordinates
  2188. */
  2189. Vector2.prototype.toString = function () {
  2190. return "{X: " + this.x + " Y:" + this.y + "}";
  2191. };
  2192. /**
  2193. * Gets class name
  2194. * @returns the string "Vector2"
  2195. */
  2196. Vector2.prototype.getClassName = function () {
  2197. return "Vector2";
  2198. };
  2199. /**
  2200. * Gets current vector hash code
  2201. * @returns the Vector2 hash code as a number
  2202. */
  2203. Vector2.prototype.getHashCode = function () {
  2204. var hash = this.x || 0;
  2205. hash = (hash * 397) ^ (this.y || 0);
  2206. return hash;
  2207. };
  2208. // Operators
  2209. /**
  2210. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2211. * @param array defines the source array
  2212. * @param index defines the offset in source array
  2213. * @returns the current Vector2
  2214. */
  2215. Vector2.prototype.toArray = function (array, index) {
  2216. if (index === void 0) { index = 0; }
  2217. array[index] = this.x;
  2218. array[index + 1] = this.y;
  2219. return this;
  2220. };
  2221. /**
  2222. * Copy the current vector to an array
  2223. * @returns a new array with 2 elements: the Vector2 coordinates.
  2224. */
  2225. Vector2.prototype.asArray = function () {
  2226. var result = new Array();
  2227. this.toArray(result, 0);
  2228. return result;
  2229. };
  2230. /**
  2231. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2232. * @param source defines the source Vector2
  2233. * @returns the current updated Vector2
  2234. */
  2235. Vector2.prototype.copyFrom = function (source) {
  2236. this.x = source.x;
  2237. this.y = source.y;
  2238. return this;
  2239. };
  2240. /**
  2241. * Sets the Vector2 coordinates with the given floats
  2242. * @param x defines the first coordinate
  2243. * @param y defines the second coordinate
  2244. * @returns the current updated Vector2
  2245. */
  2246. Vector2.prototype.copyFromFloats = function (x, y) {
  2247. this.x = x;
  2248. this.y = y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the given floats
  2253. * @param x defines the first coordinate
  2254. * @param y defines the second coordinate
  2255. * @returns the current updated Vector2
  2256. */
  2257. Vector2.prototype.set = function (x, y) {
  2258. return this.copyFromFloats(x, y);
  2259. };
  2260. /**
  2261. * Add another vector with the current one
  2262. * @param otherVector defines the other vector
  2263. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2264. */
  2265. Vector2.prototype.add = function (otherVector) {
  2266. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2267. };
  2268. /**
  2269. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2270. * @param otherVector defines the other vector
  2271. * @param result defines the target vector
  2272. * @returns the unmodified current Vector2
  2273. */
  2274. Vector2.prototype.addToRef = function (otherVector, result) {
  2275. result.x = this.x + otherVector.x;
  2276. result.y = this.y + otherVector.y;
  2277. return this;
  2278. };
  2279. /**
  2280. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2281. * @param otherVector defines the other vector
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.addInPlace = function (otherVector) {
  2285. this.x += otherVector.x;
  2286. this.y += otherVector.y;
  2287. return this;
  2288. };
  2289. /**
  2290. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2291. * @param otherVector defines the other vector
  2292. * @returns a new Vector2
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2299. * @param otherVector defines the other vector
  2300. * @returns a new Vector2
  2301. */
  2302. Vector2.prototype.subtract = function (otherVector) {
  2303. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2304. };
  2305. /**
  2306. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2307. * @param otherVector defines the other vector
  2308. * @param result defines the target vector
  2309. * @returns the unmodified current Vector2
  2310. */
  2311. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2312. result.x = this.x - otherVector.x;
  2313. result.y = this.y - otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns the current updated Vector2
  2320. */
  2321. Vector2.prototype.subtractInPlace = function (otherVector) {
  2322. this.x -= otherVector.x;
  2323. this.y -= otherVector.y;
  2324. return this;
  2325. };
  2326. /**
  2327. * Multiplies in place the current Vector2 coordinates by the given ones
  2328. * @param otherVector defines the other vector
  2329. * @returns the current updated Vector2
  2330. */
  2331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2332. this.x *= otherVector.x;
  2333. this.y *= otherVector.y;
  2334. return this;
  2335. };
  2336. /**
  2337. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2338. * @param otherVector defines the other vector
  2339. * @returns a new Vector2
  2340. */
  2341. Vector2.prototype.multiply = function (otherVector) {
  2342. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2343. };
  2344. /**
  2345. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2346. * @param otherVector defines the other vector
  2347. * @param result defines the target vector
  2348. * @returns the unmodified current Vector2
  2349. */
  2350. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2351. result.x = this.x * otherVector.x;
  2352. result.y = this.y * otherVector.y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns a new Vector2
  2360. */
  2361. Vector2.prototype.multiplyByFloats = function (x, y) {
  2362. return new Vector2(this.x * x, this.y * y);
  2363. };
  2364. /**
  2365. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2
  2368. */
  2369. Vector2.prototype.divide = function (otherVector) {
  2370. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the Vector2 divided by 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.divideToRef = function (otherVector, result) {
  2379. result.x = this.x / otherVector.x;
  2380. result.y = this.y / otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Divides the current Vector3 coordinates by the given ones
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.divideInPlace = function (otherVector) {
  2389. return this.divideToRef(otherVector, this);
  2390. };
  2391. /**
  2392. * Gets a new Vector2 with current Vector2 negated coordinates
  2393. * @returns a new Vector2
  2394. */
  2395. Vector2.prototype.negate = function () {
  2396. return new Vector2(-this.x, -this.y);
  2397. };
  2398. /**
  2399. * Multiply the Vector2 coordinates by scale
  2400. * @param scale defines the scaling factor
  2401. * @returns the current updated Vector2
  2402. */
  2403. Vector2.prototype.scaleInPlace = function (scale) {
  2404. this.x *= scale;
  2405. this.y *= scale;
  2406. return this;
  2407. };
  2408. /**
  2409. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2410. * @param scale defines the scaling factor
  2411. * @returns a new Vector2
  2412. */
  2413. Vector2.prototype.scale = function (scale) {
  2414. var result = new Vector2(0, 0);
  2415. this.scaleToRef(scale, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Scale the current Vector2 values by a factor to a given Vector2
  2420. * @param scale defines the scale factor
  2421. * @param result defines the Vector2 object where to store the result
  2422. * @returns the unmodified current Vector2
  2423. */
  2424. Vector2.prototype.scaleToRef = function (scale, result) {
  2425. result.x = this.x * scale;
  2426. result.y = this.y * scale;
  2427. return this;
  2428. };
  2429. /**
  2430. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2431. * @param scale defines the scale factor
  2432. * @param result defines the Vector2 object where to store the result
  2433. * @returns the unmodified current Vector2
  2434. */
  2435. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2436. result.x += this.x * scale;
  2437. result.y += this.y * scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Gets a boolean if two vectors are equals
  2442. * @param otherVector defines the other vector
  2443. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2444. */
  2445. Vector2.prototype.equals = function (otherVector) {
  2446. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2447. };
  2448. /**
  2449. * Gets a boolean if two vectors are equals (using an epsilon value)
  2450. * @param otherVector defines the other vector
  2451. * @param epsilon defines the minimal distance to consider equality
  2452. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2453. */
  2454. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2455. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2456. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2457. };
  2458. // Properties
  2459. /**
  2460. * Gets the length of the vector
  2461. * @returns the vector length (float)
  2462. */
  2463. Vector2.prototype.length = function () {
  2464. return Math.sqrt(this.x * this.x + this.y * this.y);
  2465. };
  2466. /**
  2467. * Gets the vector squared length
  2468. * @returns the vector squared length (float)
  2469. */
  2470. Vector2.prototype.lengthSquared = function () {
  2471. return (this.x * this.x + this.y * this.y);
  2472. };
  2473. // Methods
  2474. /**
  2475. * Normalize the vector
  2476. * @returns the current updated Vector2
  2477. */
  2478. Vector2.prototype.normalize = function () {
  2479. var len = this.length();
  2480. if (len === 0)
  2481. return this;
  2482. var num = 1.0 / len;
  2483. this.x *= num;
  2484. this.y *= num;
  2485. return this;
  2486. };
  2487. /**
  2488. * Gets a new Vector2 copied from the Vector2
  2489. * @returns a new Vector2
  2490. */
  2491. Vector2.prototype.clone = function () {
  2492. return new Vector2(this.x, this.y);
  2493. };
  2494. // Statics
  2495. /**
  2496. * Gets a new Vector2(0, 0)
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.Zero = function () {
  2500. return new Vector2(0, 0);
  2501. };
  2502. /**
  2503. * Gets a new Vector2(1, 1)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.One = function () {
  2507. return new Vector2(1, 1);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 set from the given index element of the given array
  2511. * @param array defines the data source
  2512. * @param offset defines the offset in the data source
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.FromArray = function (array, offset) {
  2516. if (offset === void 0) { offset = 0; }
  2517. return new Vector2(array[offset], array[offset + 1]);
  2518. };
  2519. /**
  2520. * Sets "result" from the given index element of the given array
  2521. * @param array defines the data source
  2522. * @param offset defines the offset in the data source
  2523. * @param result defines the target vector
  2524. */
  2525. Vector2.FromArrayToRef = function (array, offset, result) {
  2526. result.x = array[offset];
  2527. result.y = array[offset + 1];
  2528. };
  2529. /**
  2530. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2531. * @param value1 defines 1st point of control
  2532. * @param value2 defines 2nd point of control
  2533. * @param value3 defines 3rd point of control
  2534. * @param value4 defines 4th point of control
  2535. * @param amount defines the interpolation factor
  2536. * @returns a new Vector2
  2537. */
  2538. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2539. var squared = amount * amount;
  2540. var cubed = amount * squared;
  2541. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2542. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2543. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2544. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2545. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2546. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * 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".
  2551. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2552. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2553. * @param value defines the value to clamp
  2554. * @param min defines the lower limit
  2555. * @param max defines the upper limit
  2556. * @returns a new Vector2
  2557. */
  2558. Vector2.Clamp = function (value, min, max) {
  2559. var x = value.x;
  2560. x = (x > max.x) ? max.x : x;
  2561. x = (x < min.x) ? min.x : x;
  2562. var y = value.y;
  2563. y = (y > max.y) ? max.y : y;
  2564. y = (y < min.y) ? min.y : y;
  2565. return new Vector2(x, y);
  2566. };
  2567. /**
  2568. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2569. * @param value1 defines the 1st control point
  2570. * @param tangent1 defines the outgoing tangent
  2571. * @param value2 defines the 2nd control point
  2572. * @param tangent2 defines the incoming tangent
  2573. * @param amount defines the interpolation factor
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2577. var squared = amount * amount;
  2578. var cubed = amount * squared;
  2579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2581. var part3 = (cubed - (2.0 * squared)) + amount;
  2582. var part4 = cubed - squared;
  2583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2585. return new Vector2(x, y);
  2586. };
  2587. /**
  2588. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2589. * @param start defines the start vector
  2590. * @param end defines the end vector
  2591. * @param amount defines the interpolation factor
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Lerp = function (start, end, amount) {
  2595. var x = start.x + ((end.x - start.x) * amount);
  2596. var y = start.y + ((end.y - start.y) * amount);
  2597. return new Vector2(x, y);
  2598. };
  2599. /**
  2600. * Gets the dot product of the vector "left" and the vector "right"
  2601. * @param left defines first vector
  2602. * @param right defines second vector
  2603. * @returns the dot product (float)
  2604. */
  2605. Vector2.Dot = function (left, right) {
  2606. return left.x * right.x + left.y * right.y;
  2607. };
  2608. /**
  2609. * Returns a new Vector2 equal to the normalized given vector
  2610. * @param vector defines the vector to normalize
  2611. * @returns a new Vector2
  2612. */
  2613. Vector2.Normalize = function (vector) {
  2614. var newVector = vector.clone();
  2615. newVector.normalize();
  2616. return newVector;
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2620. * @param left defines 1st vector
  2621. * @param right defines 2nd vector
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Minimize = function (left, right) {
  2625. var x = (left.x < right.x) ? left.x : right.x;
  2626. var y = (left.y < right.y) ? left.y : right.y;
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2631. * @param left defines 1st vector
  2632. * @param right defines 2nd vector
  2633. * @returns a new Vector2
  2634. */
  2635. Vector2.Maximize = function (left, right) {
  2636. var x = (left.x > right.x) ? left.x : right.x;
  2637. var y = (left.y > right.y) ? left.y : right.y;
  2638. return new Vector2(x, y);
  2639. };
  2640. /**
  2641. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2642. * @param vector defines the vector to transform
  2643. * @param transformation defines the matrix to apply
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Transform = function (vector, transformation) {
  2647. var r = Vector2.Zero();
  2648. Vector2.TransformToRef(vector, transformation, r);
  2649. return r;
  2650. };
  2651. /**
  2652. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2653. * @param vector defines the vector to transform
  2654. * @param transformation defines the matrix to apply
  2655. * @param result defines the target vector
  2656. */
  2657. Vector2.TransformToRef = function (vector, transformation, result) {
  2658. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2659. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2660. result.x = x;
  2661. result.y = y;
  2662. };
  2663. /**
  2664. * Determines if a given vector is included in a triangle
  2665. * @param p defines the vector to test
  2666. * @param p0 defines 1st triangle point
  2667. * @param p1 defines 2nd triangle point
  2668. * @param p2 defines 3rd triangle point
  2669. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2670. */
  2671. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2672. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2673. var sign = a < 0 ? -1 : 1;
  2674. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2675. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2676. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2677. };
  2678. /**
  2679. * Gets the distance between the vectors "value1" and "value2"
  2680. * @param value1 defines first vector
  2681. * @param value2 defines second vector
  2682. * @returns the distance between vectors
  2683. */
  2684. Vector2.Distance = function (value1, value2) {
  2685. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2686. };
  2687. /**
  2688. * Returns the squared distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the squared distance between vectors
  2692. */
  2693. Vector2.DistanceSquared = function (value1, value2) {
  2694. var x = value1.x - value2.x;
  2695. var y = value1.y - value2.y;
  2696. return (x * x) + (y * y);
  2697. };
  2698. /**
  2699. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2700. * @param value1 defines first vector
  2701. * @param value2 defines second vector
  2702. * @returns a new Vector2
  2703. */
  2704. Vector2.Center = function (value1, value2) {
  2705. var center = value1.add(value2);
  2706. center.scaleInPlace(0.5);
  2707. return center;
  2708. };
  2709. /**
  2710. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2711. * @param p defines the middle point
  2712. * @param segA defines one point of the segment
  2713. * @param segB defines the other point of the segment
  2714. * @returns the shortest distance
  2715. */
  2716. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2717. var l2 = Vector2.DistanceSquared(segA, segB);
  2718. if (l2 === 0.0) {
  2719. return Vector2.Distance(p, segA);
  2720. }
  2721. var v = segB.subtract(segA);
  2722. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2723. var proj = segA.add(v.multiplyByFloats(t, t));
  2724. return Vector2.Distance(p, proj);
  2725. };
  2726. return Vector2;
  2727. }());
  2728. BABYLON.Vector2 = Vector2;
  2729. /**
  2730. * Classed used to store (x,y,z) vector representation
  2731. * A Vector3 is the main object used in 3D geometry
  2732. * It can represent etiher the coordinates of a point the space, either a direction
  2733. * Reminder: Babylon.js uses a left handed forward facing system
  2734. */
  2735. var Vector3 = /** @class */ (function () {
  2736. /**
  2737. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2738. * @param x defines the first coordinates (on X axis)
  2739. * @param y defines the second coordinates (on Y axis)
  2740. * @param z defines the third coordinates (on Z axis)
  2741. */
  2742. function Vector3(
  2743. /**
  2744. * Defines the first coordinates (on X axis)
  2745. */
  2746. x,
  2747. /**
  2748. * Defines the second coordinates (on Y axis)
  2749. */
  2750. y,
  2751. /**
  2752. * Defines the third coordinates (on Z axis)
  2753. */
  2754. z) {
  2755. this.x = x;
  2756. this.y = y;
  2757. this.z = z;
  2758. }
  2759. /**
  2760. * Creates a string representation of the Vector3
  2761. * @returns a string with the Vector3 coordinates.
  2762. */
  2763. Vector3.prototype.toString = function () {
  2764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2765. };
  2766. /**
  2767. * Gets the class name
  2768. * @returns the string "Vector3"
  2769. */
  2770. Vector3.prototype.getClassName = function () {
  2771. return "Vector3";
  2772. };
  2773. /**
  2774. * Creates the Vector3 hash code
  2775. * @returns a number which tends to be unique between Vector3 instances
  2776. */
  2777. Vector3.prototype.getHashCode = function () {
  2778. var hash = this.x || 0;
  2779. hash = (hash * 397) ^ (this.y || 0);
  2780. hash = (hash * 397) ^ (this.z || 0);
  2781. return hash;
  2782. };
  2783. // Operators
  2784. /**
  2785. * Creates an array containing three elements : the coordinates of the Vector3
  2786. * @returns a new array of numbers
  2787. */
  2788. Vector3.prototype.asArray = function () {
  2789. var result = [];
  2790. this.toArray(result, 0);
  2791. return result;
  2792. };
  2793. /**
  2794. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2795. * @param array defines the destination array
  2796. * @param index defines the offset in the destination array
  2797. * @returns the current Vector3
  2798. */
  2799. Vector3.prototype.toArray = function (array, index) {
  2800. if (index === void 0) { index = 0; }
  2801. array[index] = this.x;
  2802. array[index + 1] = this.y;
  2803. array[index + 2] = this.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2808. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2809. */
  2810. Vector3.prototype.toQuaternion = function () {
  2811. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2812. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2813. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2814. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2815. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2816. var cosy = Math.cos(this.y * 0.5);
  2817. var siny = Math.sin(this.y * 0.5);
  2818. result.x = coszMinusx * siny;
  2819. result.y = -sinzMinusx * siny;
  2820. result.z = sinxPlusz * cosy;
  2821. result.w = cosxPlusz * cosy;
  2822. return result;
  2823. };
  2824. /**
  2825. * Adds the given vector to the current Vector3
  2826. * @param otherVector defines the second operand
  2827. * @returns the current updated Vector3
  2828. */
  2829. Vector3.prototype.addInPlace = function (otherVector) {
  2830. this.x += otherVector.x;
  2831. this.y += otherVector.y;
  2832. this.z += otherVector.z;
  2833. return this;
  2834. };
  2835. /**
  2836. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2837. * @param otherVector defines the second operand
  2838. * @returns the resulting Vector3
  2839. */
  2840. Vector3.prototype.add = function (otherVector) {
  2841. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2842. };
  2843. /**
  2844. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2845. * @param otherVector defines the second operand
  2846. * @param result defines the Vector3 object where to store the result
  2847. * @returns the current Vector3
  2848. */
  2849. Vector3.prototype.addToRef = function (otherVector, result) {
  2850. result.x = this.x + otherVector.x;
  2851. result.y = this.y + otherVector.y;
  2852. result.z = this.z + otherVector.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Subtract the given vector from the current Vector3
  2857. * @param otherVector defines the second operand
  2858. * @returns the current updated Vector3
  2859. */
  2860. Vector3.prototype.subtractInPlace = function (otherVector) {
  2861. this.x -= otherVector.x;
  2862. this.y -= otherVector.y;
  2863. this.z -= otherVector.z;
  2864. return this;
  2865. };
  2866. /**
  2867. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2868. * @param otherVector defines the second operand
  2869. * @returns the resulting Vector3
  2870. */
  2871. Vector3.prototype.subtract = function (otherVector) {
  2872. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2873. };
  2874. /**
  2875. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2876. * @param otherVector defines the second operand
  2877. * @param result defines the Vector3 object where to store the result
  2878. * @returns the current Vector3
  2879. */
  2880. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2881. result.x = this.x - otherVector.x;
  2882. result.y = this.y - otherVector.y;
  2883. result.z = this.z - otherVector.z;
  2884. return this;
  2885. };
  2886. /**
  2887. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2888. * @param x defines the x coordinate of the operand
  2889. * @param y defines the y coordinate of the operand
  2890. * @param z defines the z coordinate of the operand
  2891. * @returns the resulting Vector3
  2892. */
  2893. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2894. return new Vector3(this.x - x, this.y - y, this.z - z);
  2895. };
  2896. /**
  2897. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2898. * @param x defines the x coordinate of the operand
  2899. * @param y defines the y coordinate of the operand
  2900. * @param z defines the z coordinate of the operand
  2901. * @param result defines the Vector3 object where to store the result
  2902. * @returns the current Vector3
  2903. */
  2904. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2905. result.x = this.x - x;
  2906. result.y = this.y - y;
  2907. result.z = this.z - z;
  2908. return this;
  2909. };
  2910. /**
  2911. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2912. * @returns a new Vector3
  2913. */
  2914. Vector3.prototype.negate = function () {
  2915. return new Vector3(-this.x, -this.y, -this.z);
  2916. };
  2917. /**
  2918. * Multiplies the Vector3 coordinates by the float "scale"
  2919. * @param scale defines the multiplier factor
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.scaleInPlace = function (scale) {
  2923. this.x *= scale;
  2924. this.y *= scale;
  2925. this.z *= scale;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2930. * @param scale defines the multiplier factor
  2931. * @returns a new Vector3
  2932. */
  2933. Vector3.prototype.scale = function (scale) {
  2934. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2935. };
  2936. /**
  2937. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2938. * @param scale defines the multiplier factor
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.scaleToRef = function (scale, result) {
  2943. result.x = this.x * scale;
  2944. result.y = this.y * scale;
  2945. result.z = this.z * scale;
  2946. return this;
  2947. };
  2948. /**
  2949. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2950. * @param scale defines the scale factor
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the unmodified current Vector3
  2953. */
  2954. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2955. result.x += this.x * scale;
  2956. result.y += this.y * scale;
  2957. result.z += this.z * scale;
  2958. return this;
  2959. };
  2960. /**
  2961. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2962. * @param otherVector defines the second operand
  2963. * @returns true if both vectors are equals
  2964. */
  2965. Vector3.prototype.equals = function (otherVector) {
  2966. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2967. };
  2968. /**
  2969. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2970. * @param otherVector defines the second operand
  2971. * @param epsilon defines the minimal distance to define values as equals
  2972. * @returns true if both vectors are distant less than epsilon
  2973. */
  2974. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2975. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2976. 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);
  2977. };
  2978. /**
  2979. * Returns true if the current Vector3 coordinates equals the given floats
  2980. * @param x defines the x coordinate of the operand
  2981. * @param y defines the y coordinate of the operand
  2982. * @param z defines the z coordinate of the operand
  2983. * @returns true if both vectors are equals
  2984. */
  2985. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2986. return this.x === x && this.y === y && this.z === z;
  2987. };
  2988. /**
  2989. * Multiplies the current Vector3 coordinates by the given ones
  2990. * @param otherVector defines the second operand
  2991. * @returns the current updated Vector3
  2992. */
  2993. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2994. this.x *= otherVector.x;
  2995. this.y *= otherVector.y;
  2996. this.z *= otherVector.z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3001. * @param otherVector defines the second operand
  3002. * @returns the new Vector3
  3003. */
  3004. Vector3.prototype.multiply = function (otherVector) {
  3005. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3006. };
  3007. /**
  3008. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3009. * @param otherVector defines the second operand
  3010. * @param result defines the Vector3 object where to store the result
  3011. * @returns the current Vector3
  3012. */
  3013. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3014. result.x = this.x * otherVector.x;
  3015. result.y = this.y * otherVector.y;
  3016. result.z = this.z * otherVector.z;
  3017. return this;
  3018. };
  3019. /**
  3020. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3021. * @param x defines the x coordinate of the operand
  3022. * @param y defines the y coordinate of the operand
  3023. * @param z defines the z coordinate of the operand
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3027. return new Vector3(this.x * x, this.y * y, this.z * z);
  3028. };
  3029. /**
  3030. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3031. * @param otherVector defines the second operand
  3032. * @returns the new Vector3
  3033. */
  3034. Vector3.prototype.divide = function (otherVector) {
  3035. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3036. };
  3037. /**
  3038. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3039. * @param otherVector defines the second operand
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the current Vector3
  3042. */
  3043. Vector3.prototype.divideToRef = function (otherVector, result) {
  3044. result.x = this.x / otherVector.x;
  3045. result.y = this.y / otherVector.y;
  3046. result.z = this.z / otherVector.z;
  3047. return this;
  3048. };
  3049. /**
  3050. * Divides the current Vector3 coordinates by the given ones.
  3051. * @param otherVector defines the second operand
  3052. * @returns the current updated Vector3
  3053. */
  3054. Vector3.prototype.divideInPlace = function (otherVector) {
  3055. return this.divideToRef(otherVector, this);
  3056. };
  3057. /**
  3058. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3059. * @param other defines the second operand
  3060. * @returns the current updated Vector3
  3061. */
  3062. Vector3.prototype.minimizeInPlace = function (other) {
  3063. if (other.x < this.x)
  3064. this.x = other.x;
  3065. if (other.y < this.y)
  3066. this.y = other.y;
  3067. if (other.z < this.z)
  3068. this.z = other.z;
  3069. return this;
  3070. };
  3071. /**
  3072. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3073. * @param other defines the second operand
  3074. * @returns the current updated Vector3
  3075. */
  3076. Vector3.prototype.maximizeInPlace = function (other) {
  3077. if (other.x > this.x)
  3078. this.x = other.x;
  3079. if (other.y > this.y)
  3080. this.y = other.y;
  3081. if (other.z > this.z)
  3082. this.z = other.z;
  3083. return this;
  3084. };
  3085. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3086. /**
  3087. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3088. */
  3089. get: function () {
  3090. var absX = Math.abs(this.x);
  3091. var absY = Math.abs(this.y);
  3092. if (absX !== absY) {
  3093. return true;
  3094. }
  3095. var absZ = Math.abs(this.z);
  3096. if (absX !== absZ) {
  3097. return true;
  3098. }
  3099. if (absY !== absZ) {
  3100. return true;
  3101. }
  3102. return false;
  3103. },
  3104. enumerable: true,
  3105. configurable: true
  3106. });
  3107. // Properties
  3108. /**
  3109. * Gets the length of the Vector3
  3110. * @returns the length of the Vecto3
  3111. */
  3112. Vector3.prototype.length = function () {
  3113. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3114. };
  3115. /**
  3116. * Gets the squared length of the Vector3
  3117. * @returns squared length of the Vector3
  3118. */
  3119. Vector3.prototype.lengthSquared = function () {
  3120. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3121. };
  3122. /**
  3123. * Normalize the current Vector3.
  3124. * Please note that this is an in place operation.
  3125. * @returns the current updated Vector3
  3126. */
  3127. Vector3.prototype.normalize = function () {
  3128. var len = this.length();
  3129. if (len === 0 || len === 1.0)
  3130. return this;
  3131. var num = 1.0 / len;
  3132. this.x *= num;
  3133. this.y *= num;
  3134. this.z *= num;
  3135. return this;
  3136. };
  3137. /**
  3138. * Normalize the current Vector3 to a new vector
  3139. * @returns the new Vector3
  3140. */
  3141. Vector3.prototype.normalizeToNew = function () {
  3142. var normalized = new Vector3(0, 0, 0);
  3143. this.normalizeToRef(normalized);
  3144. return normalized;
  3145. };
  3146. /**
  3147. * Normalize the current Vector3 to the reference
  3148. * @param reference define the Vector3 to update
  3149. * @returns the updated Vector3
  3150. */
  3151. Vector3.prototype.normalizeToRef = function (reference) {
  3152. var len = this.length();
  3153. if (len === 0 || len === 1.0) {
  3154. reference.set(this.x, this.y, this.z);
  3155. return reference;
  3156. }
  3157. var scale = 1.0 / len;
  3158. this.scaleToRef(scale, reference);
  3159. return reference;
  3160. };
  3161. /**
  3162. * Creates a new Vector3 copied from the current Vector3
  3163. * @returns the new Vector3
  3164. */
  3165. Vector3.prototype.clone = function () {
  3166. return new Vector3(this.x, this.y, this.z);
  3167. };
  3168. /**
  3169. * Copies the given vector coordinates to the current Vector3 ones
  3170. * @param source defines the source Vector3
  3171. * @returns the current updated Vector3
  3172. */
  3173. Vector3.prototype.copyFrom = function (source) {
  3174. this.x = source.x;
  3175. this.y = source.y;
  3176. this.z = source.z;
  3177. return this;
  3178. };
  3179. /**
  3180. * Copies the given floats to the current Vector3 coordinates
  3181. * @param x defines the x coordinate of the operand
  3182. * @param y defines the y coordinate of the operand
  3183. * @param z defines the z coordinate of the operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3187. this.x = x;
  3188. this.y = y;
  3189. this.z = z;
  3190. return this;
  3191. };
  3192. /**
  3193. * Copies the given floats to the current Vector3 coordinates
  3194. * @param x defines the x coordinate of the operand
  3195. * @param y defines the y coordinate of the operand
  3196. * @param z defines the z coordinate of the operand
  3197. * @returns the current updated Vector3
  3198. */
  3199. Vector3.prototype.set = function (x, y, z) {
  3200. return this.copyFromFloats(x, y, z);
  3201. };
  3202. // Statics
  3203. /**
  3204. * Get the clip factor between two vectors
  3205. * @param vector0 defines the first operand
  3206. * @param vector1 defines the second operand
  3207. * @param axis defines the axis to use
  3208. * @param size defines the size along the axis
  3209. * @returns the clip factor
  3210. */
  3211. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3212. var d0 = Vector3.Dot(vector0, axis) - size;
  3213. var d1 = Vector3.Dot(vector1, axis) - size;
  3214. var s = d0 / (d0 - d1);
  3215. return s;
  3216. };
  3217. /**
  3218. * Get angle between two vectors
  3219. * @param vector0 angle between vector0 and vector1
  3220. * @param vector1 angle between vector0 and vector1
  3221. * @param normal direction of the normal
  3222. * @return the angle between vector0 and vector1
  3223. */
  3224. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3225. var v0 = vector0.clone().normalize();
  3226. var v1 = vector1.clone().normalize();
  3227. var dot = Vector3.Dot(v0, v1);
  3228. var n = Vector3.Cross(v0, v1);
  3229. if (Vector3.Dot(n, normal) > 0) {
  3230. return Math.acos(dot);
  3231. }
  3232. return -Math.acos(dot);
  3233. };
  3234. /**
  3235. * Returns a new Vector3 set from the index "offset" of the given array
  3236. * @param array defines the source array
  3237. * @param offset defines the offset in the source array
  3238. * @returns the new Vector3
  3239. */
  3240. Vector3.FromArray = function (array, offset) {
  3241. if (!offset) {
  3242. offset = 0;
  3243. }
  3244. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3248. * This function is deprecated. Use FromArray instead
  3249. * @param array defines the source array
  3250. * @param offset defines the offset in the source array
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.FromFloatArray = function (array, offset) {
  3254. return Vector3.FromArray(array, offset);
  3255. };
  3256. /**
  3257. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3258. * @param array defines the source array
  3259. * @param offset defines the offset in the source array
  3260. * @param result defines the Vector3 where to store the result
  3261. */
  3262. Vector3.FromArrayToRef = function (array, offset, result) {
  3263. result.x = array[offset];
  3264. result.y = array[offset + 1];
  3265. result.z = array[offset + 2];
  3266. };
  3267. /**
  3268. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3269. * This function is deprecated. Use FromArrayToRef instead.
  3270. * @param array defines the source array
  3271. * @param offset defines the offset in the source array
  3272. * @param result defines the Vector3 where to store the result
  3273. */
  3274. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3275. return Vector3.FromArrayToRef(array, offset, result);
  3276. };
  3277. /**
  3278. * Sets the given vector "result" with the given floats.
  3279. * @param x defines the x coordinate of the source
  3280. * @param y defines the y coordinate of the source
  3281. * @param z defines the z coordinate of the source
  3282. * @param result defines the Vector3 where to store the result
  3283. */
  3284. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3291. * @returns a new empty Vector3
  3292. */
  3293. Vector3.Zero = function () {
  3294. return new Vector3(0.0, 0.0, 0.0);
  3295. };
  3296. /**
  3297. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3298. * @returns a new unit Vector3
  3299. */
  3300. Vector3.One = function () {
  3301. return new Vector3(1.0, 1.0, 1.0);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3305. * @returns a new up Vector3
  3306. */
  3307. Vector3.Up = function () {
  3308. return new Vector3(0.0, 1.0, 0.0);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3312. * @returns a new forward Vector3
  3313. */
  3314. Vector3.Forward = function () {
  3315. return new Vector3(0.0, 0.0, 1.0);
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3319. * @returns a new right Vector3
  3320. */
  3321. Vector3.Right = function () {
  3322. return new Vector3(1.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3326. * @returns a new left Vector3
  3327. */
  3328. Vector3.Left = function () {
  3329. return new Vector3(-1.0, 0.0, 0.0);
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3333. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3334. * @param vector defines the Vector3 to transform
  3335. * @param transformation defines the transformation matrix
  3336. * @returns the transformed Vector3
  3337. */
  3338. Vector3.TransformCoordinates = function (vector, transformation) {
  3339. var result = Vector3.Zero();
  3340. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3341. return result;
  3342. };
  3343. /**
  3344. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3345. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3346. * @param vector defines the Vector3 to transform
  3347. * @param transformation defines the transformation matrix
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3351. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3352. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3353. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3354. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3355. result.x = x / w;
  3356. result.y = y / w;
  3357. result.z = z / w;
  3358. };
  3359. /**
  3360. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3361. * This method computes tranformed coordinates only, not transformed direction vectors
  3362. * @param x define the x coordinate of the source vector
  3363. * @param y define the y coordinate of the source vector
  3364. * @param z define the z coordinate of the source vector
  3365. * @param transformation defines the transformation matrix
  3366. * @param result defines the Vector3 where to store the result
  3367. */
  3368. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3369. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3370. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3371. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3372. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3373. result.x = rx / rw;
  3374. result.y = ry / rw;
  3375. result.z = rz / rw;
  3376. };
  3377. /**
  3378. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3379. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3380. * @param vector defines the Vector3 to transform
  3381. * @param transformation defines the transformation matrix
  3382. * @returns the new Vector3
  3383. */
  3384. Vector3.TransformNormal = function (vector, transformation) {
  3385. var result = Vector3.Zero();
  3386. Vector3.TransformNormalToRef(vector, transformation, result);
  3387. return result;
  3388. };
  3389. /**
  3390. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3391. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3392. * @param vector defines the Vector3 to transform
  3393. * @param transformation defines the transformation matrix
  3394. * @param result defines the Vector3 where to store the result
  3395. */
  3396. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3397. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3398. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3399. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3400. result.x = x;
  3401. result.y = y;
  3402. result.z = z;
  3403. };
  3404. /**
  3405. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3406. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3407. * @param x define the x coordinate of the source vector
  3408. * @param y define the y coordinate of the source vector
  3409. * @param z define the z coordinate of the source vector
  3410. * @param transformation defines the transformation matrix
  3411. * @param result defines the Vector3 where to store the result
  3412. */
  3413. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3414. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3415. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3416. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3417. };
  3418. /**
  3419. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3420. * @param value1 defines the first control point
  3421. * @param value2 defines the second control point
  3422. * @param value3 defines the third control point
  3423. * @param value4 defines the fourth control point
  3424. * @param amount defines the amount on the spline to use
  3425. * @returns the new Vector3
  3426. */
  3427. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3428. var squared = amount * amount;
  3429. var cubed = amount * squared;
  3430. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3431. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3432. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3433. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3434. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3435. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3436. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3437. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3438. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3439. return new Vector3(x, y, z);
  3440. };
  3441. /**
  3442. * 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"
  3443. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3444. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3445. * @param value defines the current value
  3446. * @param min defines the lower range value
  3447. * @param max defines the upper range value
  3448. * @returns the new Vector3
  3449. */
  3450. Vector3.Clamp = function (value, min, max) {
  3451. var x = value.x;
  3452. x = (x > max.x) ? max.x : x;
  3453. x = (x < min.x) ? min.x : x;
  3454. var y = value.y;
  3455. y = (y > max.y) ? max.y : y;
  3456. y = (y < min.y) ? min.y : y;
  3457. var z = value.z;
  3458. z = (z > max.z) ? max.z : z;
  3459. z = (z < min.z) ? min.z : z;
  3460. return new Vector3(x, y, z);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3464. * @param value1 defines the first control point
  3465. * @param tangent1 defines the first tangent vector
  3466. * @param value2 defines the second control point
  3467. * @param tangent2 defines the second tangent vector
  3468. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3469. * @returns the new Vector3
  3470. */
  3471. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3472. var squared = amount * amount;
  3473. var cubed = amount * squared;
  3474. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3475. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3476. var part3 = (cubed - (2.0 * squared)) + amount;
  3477. var part4 = cubed - squared;
  3478. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3479. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3480. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3481. return new Vector3(x, y, z);
  3482. };
  3483. /**
  3484. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3485. * @param start defines the start value
  3486. * @param end defines the end value
  3487. * @param amount max defines amount between both (between 0 and 1)
  3488. * @returns the new Vector3
  3489. */
  3490. Vector3.Lerp = function (start, end, amount) {
  3491. var result = new Vector3(0, 0, 0);
  3492. Vector3.LerpToRef(start, end, amount, result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3497. * @param start defines the start value
  3498. * @param end defines the end value
  3499. * @param amount max defines amount between both (between 0 and 1)
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.LerpToRef = function (start, end, amount, result) {
  3503. result.x = start.x + ((end.x - start.x) * amount);
  3504. result.y = start.y + ((end.y - start.y) * amount);
  3505. result.z = start.z + ((end.z - start.z) * amount);
  3506. };
  3507. /**
  3508. * Returns the dot product (float) between the vectors "left" and "right"
  3509. * @param left defines the left operand
  3510. * @param right defines the right operand
  3511. * @returns the dot product
  3512. */
  3513. Vector3.Dot = function (left, right) {
  3514. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3515. };
  3516. /**
  3517. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3518. * The cross product is then orthogonal to both "left" and "right"
  3519. * @param left defines the left operand
  3520. * @param right defines the right operand
  3521. * @returns the cross product
  3522. */
  3523. Vector3.Cross = function (left, right) {
  3524. var result = Vector3.Zero();
  3525. Vector3.CrossToRef(left, right, result);
  3526. return result;
  3527. };
  3528. /**
  3529. * Sets the given vector "result" with the cross product of "left" and "right"
  3530. * The cross product is then orthogonal to both "left" and "right"
  3531. * @param left defines the left operand
  3532. * @param right defines the right operand
  3533. * @param result defines the Vector3 where to store the result
  3534. */
  3535. Vector3.CrossToRef = function (left, right, result) {
  3536. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3537. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3538. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3539. result.copyFrom(MathTmp.Vector3[0]);
  3540. };
  3541. /**
  3542. * Returns a new Vector3 as the normalization of the given vector
  3543. * @param vector defines the Vector3 to normalize
  3544. * @returns the new Vector3
  3545. */
  3546. Vector3.Normalize = function (vector) {
  3547. var result = Vector3.Zero();
  3548. Vector3.NormalizeToRef(vector, result);
  3549. return result;
  3550. };
  3551. /**
  3552. * Sets the given vector "result" with the normalization of the given first vector
  3553. * @param vector defines the Vector3 to normalize
  3554. * @param result defines the Vector3 where to store the result
  3555. */
  3556. Vector3.NormalizeToRef = function (vector, result) {
  3557. result.copyFrom(vector);
  3558. result.normalize();
  3559. };
  3560. /**
  3561. * Project a Vector3 onto screen space
  3562. * @param vector defines the Vector3 to project
  3563. * @param world defines the world matrix to use
  3564. * @param transform defines the transform (view x projection) matrix to use
  3565. * @param viewport defines the screen viewport to use
  3566. * @returns the new Vector3
  3567. */
  3568. Vector3.Project = function (vector, world, transform, viewport) {
  3569. var cw = viewport.width;
  3570. var ch = viewport.height;
  3571. var cx = viewport.x;
  3572. var cy = viewport.y;
  3573. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3574. 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);
  3575. var matrix = MathTmp.Matrix[0];
  3576. world.multiplyToRef(transform, matrix);
  3577. matrix.multiplyToRef(viewportMatrix, matrix);
  3578. return Vector3.TransformCoordinates(vector, matrix);
  3579. };
  3580. /**
  3581. * Unproject from screen space to object space
  3582. * @param source defines the screen space Vector3 to use
  3583. * @param viewportWidth defines the current width of the viewport
  3584. * @param viewportHeight defines the current height of the viewport
  3585. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3586. * @param transform defines the transform (view x projection) matrix to use
  3587. * @returns the new Vector3
  3588. */
  3589. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3590. var matrix = MathTmp.Matrix[0];
  3591. world.multiplyToRef(transform, matrix);
  3592. matrix.invert();
  3593. source.x = source.x / viewportWidth * 2 - 1;
  3594. source.y = -(source.y / viewportHeight * 2 - 1);
  3595. var vector = Vector3.TransformCoordinates(source, matrix);
  3596. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3597. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3598. vector = vector.scale(1.0 / num);
  3599. }
  3600. return vector;
  3601. };
  3602. /**
  3603. * Unproject from screen space to object space
  3604. * @param source defines the screen space Vector3 to use
  3605. * @param viewportWidth defines the current width of the viewport
  3606. * @param viewportHeight defines the current height of the viewport
  3607. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3608. * @param view defines the view matrix to use
  3609. * @param projection defines the projection matrix to use
  3610. * @returns the new Vector3
  3611. */
  3612. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3613. var result = Vector3.Zero();
  3614. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3615. return result;
  3616. };
  3617. /**
  3618. * Unproject from screen space to object space
  3619. * @param source defines the screen space Vector3 to use
  3620. * @param viewportWidth defines the current width of the viewport
  3621. * @param viewportHeight defines the current height of the viewport
  3622. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3623. * @param view defines the view matrix to use
  3624. * @param projection defines the projection matrix to use
  3625. * @param result defines the Vector3 where to store the result
  3626. */
  3627. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3628. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3629. };
  3630. /**
  3631. * Unproject from screen space to object space
  3632. * @param sourceX defines the screen space x coordinate to use
  3633. * @param sourceY defines the screen space y coordinate to use
  3634. * @param sourceZ defines the screen space z coordinate to use
  3635. * @param viewportWidth defines the current width of the viewport
  3636. * @param viewportHeight defines the current height of the viewport
  3637. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3638. * @param view defines the view matrix to use
  3639. * @param projection defines the projection matrix to use
  3640. * @param result defines the Vector3 where to store the result
  3641. */
  3642. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3643. var matrix = MathTmp.Matrix[0];
  3644. world.multiplyToRef(view, matrix);
  3645. matrix.multiplyToRef(projection, matrix);
  3646. matrix.invert();
  3647. var screenSource = MathTmp.Vector3[0];
  3648. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3649. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3650. screenSource.z = 2 * sourceZ - 1.0;
  3651. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3652. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3653. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3654. result.scaleInPlace(1.0 / num);
  3655. }
  3656. };
  3657. /**
  3658. * Gets the minimal coordinate values between two Vector3
  3659. * @param left defines the first operand
  3660. * @param right defines the second operand
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Minimize = function (left, right) {
  3664. var min = left.clone();
  3665. min.minimizeInPlace(right);
  3666. return min;
  3667. };
  3668. /**
  3669. * Gets the maximal coordinate values between two Vector3
  3670. * @param left defines the first operand
  3671. * @param right defines the second operand
  3672. * @returns the new Vector3
  3673. */
  3674. Vector3.Maximize = function (left, right) {
  3675. var max = left.clone();
  3676. max.maximizeInPlace(right);
  3677. return max;
  3678. };
  3679. /**
  3680. * Returns the distance between the vectors "value1" and "value2"
  3681. * @param value1 defines the first operand
  3682. * @param value2 defines the second operand
  3683. * @returns the distance
  3684. */
  3685. Vector3.Distance = function (value1, value2) {
  3686. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3687. };
  3688. /**
  3689. * Returns the squared distance between the vectors "value1" and "value2"
  3690. * @param value1 defines the first operand
  3691. * @param value2 defines the second operand
  3692. * @returns the squared distance
  3693. */
  3694. Vector3.DistanceSquared = function (value1, value2) {
  3695. var x = value1.x - value2.x;
  3696. var y = value1.y - value2.y;
  3697. var z = value1.z - value2.z;
  3698. return (x * x) + (y * y) + (z * z);
  3699. };
  3700. /**
  3701. * Returns a new Vector3 located at the center between "value1" and "value2"
  3702. * @param value1 defines the first operand
  3703. * @param value2 defines the second operand
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.Center = function (value1, value2) {
  3707. var center = value1.add(value2);
  3708. center.scaleInPlace(0.5);
  3709. return center;
  3710. };
  3711. /**
  3712. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3713. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3714. * to something in order to rotate it from its local system to the given target system
  3715. * Note: axis1, axis2 and axis3 are normalized during this operation
  3716. * @param axis1 defines the first axis
  3717. * @param axis2 defines the second axis
  3718. * @param axis3 defines the third axis
  3719. * @returns a new Vector3
  3720. */
  3721. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3722. var rotation = Vector3.Zero();
  3723. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3724. return rotation;
  3725. };
  3726. /**
  3727. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3728. * @param axis1 defines the first axis
  3729. * @param axis2 defines the second axis
  3730. * @param axis3 defines the third axis
  3731. * @param ref defines the Vector3 where to store the result
  3732. */
  3733. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3734. var quat = MathTmp.Quaternion[0];
  3735. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3736. quat.toEulerAnglesToRef(ref);
  3737. };
  3738. return Vector3;
  3739. }());
  3740. BABYLON.Vector3 = Vector3;
  3741. //Vector4 class created for EulerAngle class conversion to Quaternion
  3742. var Vector4 = /** @class */ (function () {
  3743. /**
  3744. * Creates a Vector4 object from the given floats.
  3745. */
  3746. function Vector4(x, y, z, w) {
  3747. this.x = x;
  3748. this.y = y;
  3749. this.z = z;
  3750. this.w = w;
  3751. }
  3752. /**
  3753. * Returns the string with the Vector4 coordinates.
  3754. */
  3755. Vector4.prototype.toString = function () {
  3756. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3757. };
  3758. /**
  3759. * Returns the string "Vector4".
  3760. */
  3761. Vector4.prototype.getClassName = function () {
  3762. return "Vector4";
  3763. };
  3764. /**
  3765. * Returns the Vector4 hash code.
  3766. */
  3767. Vector4.prototype.getHashCode = function () {
  3768. var hash = this.x || 0;
  3769. hash = (hash * 397) ^ (this.y || 0);
  3770. hash = (hash * 397) ^ (this.z || 0);
  3771. hash = (hash * 397) ^ (this.w || 0);
  3772. return hash;
  3773. };
  3774. // Operators
  3775. /**
  3776. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3777. */
  3778. Vector4.prototype.asArray = function () {
  3779. var result = new Array();
  3780. this.toArray(result, 0);
  3781. return result;
  3782. };
  3783. /**
  3784. * Populates the given array from the given index with the Vector4 coordinates.
  3785. * Returns the Vector4.
  3786. */
  3787. Vector4.prototype.toArray = function (array, index) {
  3788. if (index === undefined) {
  3789. index = 0;
  3790. }
  3791. array[index] = this.x;
  3792. array[index + 1] = this.y;
  3793. array[index + 2] = this.z;
  3794. array[index + 3] = this.w;
  3795. return this;
  3796. };
  3797. /**
  3798. * Adds the given vector to the current Vector4.
  3799. * Returns the updated Vector4.
  3800. */
  3801. Vector4.prototype.addInPlace = function (otherVector) {
  3802. this.x += otherVector.x;
  3803. this.y += otherVector.y;
  3804. this.z += otherVector.z;
  3805. this.w += otherVector.w;
  3806. return this;
  3807. };
  3808. /**
  3809. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3810. */
  3811. Vector4.prototype.add = function (otherVector) {
  3812. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3813. };
  3814. /**
  3815. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3816. * Returns the current Vector4.
  3817. */
  3818. Vector4.prototype.addToRef = function (otherVector, result) {
  3819. result.x = this.x + otherVector.x;
  3820. result.y = this.y + otherVector.y;
  3821. result.z = this.z + otherVector.z;
  3822. result.w = this.w + otherVector.w;
  3823. return this;
  3824. };
  3825. /**
  3826. * Subtract in place the given vector from the current Vector4.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.subtractInPlace = function (otherVector) {
  3830. this.x -= otherVector.x;
  3831. this.y -= otherVector.y;
  3832. this.z -= otherVector.z;
  3833. this.w -= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3838. */
  3839. Vector4.prototype.subtract = function (otherVector) {
  3840. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3841. };
  3842. /**
  3843. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3847. result.x = this.x - otherVector.x;
  3848. result.y = this.y - otherVector.y;
  3849. result.z = this.z - otherVector.z;
  3850. result.w = this.w - otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3858. };
  3859. /**
  3860. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3861. * Returns the current Vector4.
  3862. */
  3863. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3864. result.x = this.x - x;
  3865. result.y = this.y - y;
  3866. result.z = this.z - z;
  3867. result.w = this.w - w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3872. */
  3873. Vector4.prototype.negate = function () {
  3874. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3875. };
  3876. /**
  3877. * Multiplies the current Vector4 coordinates by scale (float).
  3878. * Returns the updated Vector4.
  3879. */
  3880. Vector4.prototype.scaleInPlace = function (scale) {
  3881. this.x *= scale;
  3882. this.y *= scale;
  3883. this.z *= scale;
  3884. this.w *= scale;
  3885. return this;
  3886. };
  3887. /**
  3888. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3889. */
  3890. Vector4.prototype.scale = function (scale) {
  3891. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3892. };
  3893. /**
  3894. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3895. * Returns the current Vector4.
  3896. */
  3897. Vector4.prototype.scaleToRef = function (scale, result) {
  3898. result.x = this.x * scale;
  3899. result.y = this.y * scale;
  3900. result.z = this.z * scale;
  3901. result.w = this.w * scale;
  3902. return this;
  3903. };
  3904. /**
  3905. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3906. * @param scale defines the scale factor
  3907. * @param result defines the Vector4 object where to store the result
  3908. * @returns the unmodified current Vector4
  3909. */
  3910. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3911. result.x += this.x * scale;
  3912. result.y += this.y * scale;
  3913. result.z += this.z * scale;
  3914. result.w += this.w * scale;
  3915. return this;
  3916. };
  3917. /**
  3918. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3919. */
  3920. Vector4.prototype.equals = function (otherVector) {
  3921. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3922. };
  3923. /**
  3924. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3925. */
  3926. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3928. return otherVector
  3929. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3930. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3931. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3932. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3933. };
  3934. /**
  3935. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3936. */
  3937. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3938. return this.x === x && this.y === y && this.z === z && this.w === w;
  3939. };
  3940. /**
  3941. * Multiplies in place the current Vector4 by the given one.
  3942. * Returns the updated Vector4.
  3943. */
  3944. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3945. this.x *= otherVector.x;
  3946. this.y *= otherVector.y;
  3947. this.z *= otherVector.z;
  3948. this.w *= otherVector.w;
  3949. return this;
  3950. };
  3951. /**
  3952. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3953. */
  3954. Vector4.prototype.multiply = function (otherVector) {
  3955. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3956. };
  3957. /**
  3958. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3959. * Returns the current Vector4.
  3960. */
  3961. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3962. result.x = this.x * otherVector.x;
  3963. result.y = this.y * otherVector.y;
  3964. result.z = this.z * otherVector.z;
  3965. result.w = this.w * otherVector.w;
  3966. return this;
  3967. };
  3968. /**
  3969. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3970. */
  3971. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3972. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3973. };
  3974. /**
  3975. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3976. */
  3977. Vector4.prototype.divide = function (otherVector) {
  3978. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3979. };
  3980. /**
  3981. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3982. * Returns the current Vector4.
  3983. */
  3984. Vector4.prototype.divideToRef = function (otherVector, result) {
  3985. result.x = this.x / otherVector.x;
  3986. result.y = this.y / otherVector.y;
  3987. result.z = this.z / otherVector.z;
  3988. result.w = this.w / otherVector.w;
  3989. return this;
  3990. };
  3991. /**
  3992. * Divides the current Vector3 coordinates by the given ones.
  3993. * @returns the updated Vector3.
  3994. */
  3995. Vector4.prototype.divideInPlace = function (otherVector) {
  3996. return this.divideToRef(otherVector, this);
  3997. };
  3998. /**
  3999. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4000. * @param other defines the second operand
  4001. * @returns the current updated Vector4
  4002. */
  4003. Vector4.prototype.minimizeInPlace = function (other) {
  4004. if (other.x < this.x)
  4005. this.x = other.x;
  4006. if (other.y < this.y)
  4007. this.y = other.y;
  4008. if (other.z < this.z)
  4009. this.z = other.z;
  4010. if (other.w < this.w)
  4011. this.w = other.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4016. * @param other defines the second operand
  4017. * @returns the current updated Vector4
  4018. */
  4019. Vector4.prototype.maximizeInPlace = function (other) {
  4020. if (other.x > this.x)
  4021. this.x = other.x;
  4022. if (other.y > this.y)
  4023. this.y = other.y;
  4024. if (other.z > this.z)
  4025. this.z = other.z;
  4026. if (other.w > this.w)
  4027. this.w = other.w;
  4028. return this;
  4029. };
  4030. // Properties
  4031. /**
  4032. * Returns the Vector4 length (float).
  4033. */
  4034. Vector4.prototype.length = function () {
  4035. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4036. };
  4037. /**
  4038. * Returns the Vector4 squared length (float).
  4039. */
  4040. Vector4.prototype.lengthSquared = function () {
  4041. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4042. };
  4043. // Methods
  4044. /**
  4045. * Normalizes in place the Vector4.
  4046. * Returns the updated Vector4.
  4047. */
  4048. Vector4.prototype.normalize = function () {
  4049. var len = this.length();
  4050. if (len === 0)
  4051. return this;
  4052. var num = 1.0 / len;
  4053. this.x *= num;
  4054. this.y *= num;
  4055. this.z *= num;
  4056. this.w *= num;
  4057. return this;
  4058. };
  4059. /**
  4060. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4061. */
  4062. Vector4.prototype.toVector3 = function () {
  4063. return new Vector3(this.x, this.y, this.z);
  4064. };
  4065. /**
  4066. * Returns a new Vector4 copied from the current one.
  4067. */
  4068. Vector4.prototype.clone = function () {
  4069. return new Vector4(this.x, this.y, this.z, this.w);
  4070. };
  4071. /**
  4072. * Updates the current Vector4 with the given one coordinates.
  4073. * Returns the updated Vector4.
  4074. */
  4075. Vector4.prototype.copyFrom = function (source) {
  4076. this.x = source.x;
  4077. this.y = source.y;
  4078. this.z = source.z;
  4079. this.w = source.w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Updates the current Vector4 coordinates with the given floats.
  4084. * Returns the updated Vector4.
  4085. */
  4086. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4087. this.x = x;
  4088. this.y = y;
  4089. this.z = z;
  4090. this.w = w;
  4091. return this;
  4092. };
  4093. /**
  4094. * Updates the current Vector4 coordinates with the given floats.
  4095. * Returns the updated Vector4.
  4096. */
  4097. Vector4.prototype.set = function (x, y, z, w) {
  4098. return this.copyFromFloats(x, y, z, w);
  4099. };
  4100. // Statics
  4101. /**
  4102. * Returns a new Vector4 set from the starting index of the given array.
  4103. */
  4104. Vector4.FromArray = function (array, offset) {
  4105. if (!offset) {
  4106. offset = 0;
  4107. }
  4108. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4109. };
  4110. /**
  4111. * Updates the given vector "result" from the starting index of the given array.
  4112. */
  4113. Vector4.FromArrayToRef = function (array, offset, result) {
  4114. result.x = array[offset];
  4115. result.y = array[offset + 1];
  4116. result.z = array[offset + 2];
  4117. result.w = array[offset + 3];
  4118. };
  4119. /**
  4120. * Updates the given vector "result" from the starting index of the given Float32Array.
  4121. */
  4122. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4123. Vector4.FromArrayToRef(array, offset, result);
  4124. };
  4125. /**
  4126. * Updates the given vector "result" coordinates from the given floats.
  4127. */
  4128. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4129. result.x = x;
  4130. result.y = y;
  4131. result.z = z;
  4132. result.w = w;
  4133. };
  4134. /**
  4135. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4136. */
  4137. Vector4.Zero = function () {
  4138. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4139. };
  4140. /**
  4141. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4142. */
  4143. Vector4.One = function () {
  4144. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4145. };
  4146. /**
  4147. * Returns a new normalized Vector4 from the given one.
  4148. */
  4149. Vector4.Normalize = function (vector) {
  4150. var result = Vector4.Zero();
  4151. Vector4.NormalizeToRef(vector, result);
  4152. return result;
  4153. };
  4154. /**
  4155. * Updates the given vector "result" from the normalization of the given one.
  4156. */
  4157. Vector4.NormalizeToRef = function (vector, result) {
  4158. result.copyFrom(vector);
  4159. result.normalize();
  4160. };
  4161. Vector4.Minimize = function (left, right) {
  4162. var min = left.clone();
  4163. min.minimizeInPlace(right);
  4164. return min;
  4165. };
  4166. Vector4.Maximize = function (left, right) {
  4167. var max = left.clone();
  4168. max.maximizeInPlace(right);
  4169. return max;
  4170. };
  4171. /**
  4172. * Returns the distance (float) between the vectors "value1" and "value2".
  4173. */
  4174. Vector4.Distance = function (value1, value2) {
  4175. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4176. };
  4177. /**
  4178. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4179. */
  4180. Vector4.DistanceSquared = function (value1, value2) {
  4181. var x = value1.x - value2.x;
  4182. var y = value1.y - value2.y;
  4183. var z = value1.z - value2.z;
  4184. var w = value1.w - value2.w;
  4185. return (x * x) + (y * y) + (z * z) + (w * w);
  4186. };
  4187. /**
  4188. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4189. */
  4190. Vector4.Center = function (value1, value2) {
  4191. var center = value1.add(value2);
  4192. center.scaleInPlace(0.5);
  4193. return center;
  4194. };
  4195. /**
  4196. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4197. * This methods computes transformed normalized direction vectors only.
  4198. */
  4199. Vector4.TransformNormal = function (vector, transformation) {
  4200. var result = Vector4.Zero();
  4201. Vector4.TransformNormalToRef(vector, transformation, result);
  4202. return result;
  4203. };
  4204. /**
  4205. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4206. * This methods computes transformed normalized direction vectors only.
  4207. */
  4208. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4209. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4210. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4211. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4212. result.x = x;
  4213. result.y = y;
  4214. result.z = z;
  4215. result.w = vector.w;
  4216. };
  4217. /**
  4218. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4219. * This methods computes transformed normalized direction vectors only.
  4220. */
  4221. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4222. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4223. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4224. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4225. result.w = w;
  4226. };
  4227. return Vector4;
  4228. }());
  4229. BABYLON.Vector4 = Vector4;
  4230. var Size = /** @class */ (function () {
  4231. /**
  4232. * Creates a Size object from the given width and height (floats).
  4233. */
  4234. function Size(width, height) {
  4235. this.width = width;
  4236. this.height = height;
  4237. }
  4238. // Returns a string with the Size width and height.
  4239. Size.prototype.toString = function () {
  4240. return "{W: " + this.width + ", H: " + this.height + "}";
  4241. };
  4242. /**
  4243. * Returns the string "Size"
  4244. */
  4245. Size.prototype.getClassName = function () {
  4246. return "Size";
  4247. };
  4248. /**
  4249. * Returns the Size hash code.
  4250. */
  4251. Size.prototype.getHashCode = function () {
  4252. var hash = this.width || 0;
  4253. hash = (hash * 397) ^ (this.height || 0);
  4254. return hash;
  4255. };
  4256. /**
  4257. * Updates the current size from the given one.
  4258. * Returns the updated Size.
  4259. */
  4260. Size.prototype.copyFrom = function (src) {
  4261. this.width = src.width;
  4262. this.height = src.height;
  4263. };
  4264. /**
  4265. * Updates in place the current Size from the given floats.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFromFloats = function (width, height) {
  4269. this.width = width;
  4270. this.height = height;
  4271. return this;
  4272. };
  4273. /**
  4274. * Updates in place the current Size from the given floats.
  4275. * Returns the updated Size.
  4276. */
  4277. Size.prototype.set = function (width, height) {
  4278. return this.copyFromFloats(width, height);
  4279. };
  4280. /**
  4281. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4282. */
  4283. Size.prototype.multiplyByFloats = function (w, h) {
  4284. return new Size(this.width * w, this.height * h);
  4285. };
  4286. /**
  4287. * Returns a new Size copied from the given one.
  4288. */
  4289. Size.prototype.clone = function () {
  4290. return new Size(this.width, this.height);
  4291. };
  4292. /**
  4293. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4294. */
  4295. Size.prototype.equals = function (other) {
  4296. if (!other) {
  4297. return false;
  4298. }
  4299. return (this.width === other.width) && (this.height === other.height);
  4300. };
  4301. Object.defineProperty(Size.prototype, "surface", {
  4302. /**
  4303. * Returns the surface of the Size : width * height (float).
  4304. */
  4305. get: function () {
  4306. return this.width * this.height;
  4307. },
  4308. enumerable: true,
  4309. configurable: true
  4310. });
  4311. /**
  4312. * Returns a new Size set to (0.0, 0.0)
  4313. */
  4314. Size.Zero = function () {
  4315. return new Size(0.0, 0.0);
  4316. };
  4317. /**
  4318. * Returns a new Size set as the addition result of the current Size and the given one.
  4319. */
  4320. Size.prototype.add = function (otherSize) {
  4321. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4322. return r;
  4323. };
  4324. /**
  4325. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4326. */
  4327. Size.prototype.subtract = function (otherSize) {
  4328. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4329. return r;
  4330. };
  4331. /**
  4332. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4333. */
  4334. Size.Lerp = function (start, end, amount) {
  4335. var w = start.width + ((end.width - start.width) * amount);
  4336. var h = start.height + ((end.height - start.height) * amount);
  4337. return new Size(w, h);
  4338. };
  4339. return Size;
  4340. }());
  4341. BABYLON.Size = Size;
  4342. /**
  4343. * Class used to store quaternion data
  4344. * @see https://en.wikipedia.org/wiki/Quaternion
  4345. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4346. */
  4347. var Quaternion = /** @class */ (function () {
  4348. /**
  4349. * Creates a new Quaternion from the given floats
  4350. * @param x defines the first component (0 by default)
  4351. * @param y defines the second component (0 by default)
  4352. * @param z defines the third component (0 by default)
  4353. * @param w defines the fourth component (1.0 by default)
  4354. */
  4355. function Quaternion(
  4356. /** defines the first component (0 by default) */
  4357. x,
  4358. /** defines the second component (0 by default) */
  4359. y,
  4360. /** defines the third component (0 by default) */
  4361. z,
  4362. /** defines the fourth component (1.0 by default) */
  4363. w) {
  4364. if (x === void 0) { x = 0.0; }
  4365. if (y === void 0) { y = 0.0; }
  4366. if (z === void 0) { z = 0.0; }
  4367. if (w === void 0) { w = 1.0; }
  4368. this.x = x;
  4369. this.y = y;
  4370. this.z = z;
  4371. this.w = w;
  4372. }
  4373. /**
  4374. * Gets a string representation for the current quaternion
  4375. * @returns a string with the Quaternion coordinates
  4376. */
  4377. Quaternion.prototype.toString = function () {
  4378. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4379. };
  4380. /**
  4381. * Gets the class name of the quaternion
  4382. * @returns the string "Quaternion"
  4383. */
  4384. Quaternion.prototype.getClassName = function () {
  4385. return "Quaternion";
  4386. };
  4387. /**
  4388. * Gets a hash code for this quaternion
  4389. * @returns the quaternion hash code
  4390. */
  4391. Quaternion.prototype.getHashCode = function () {
  4392. var hash = this.x || 0;
  4393. hash = (hash * 397) ^ (this.y || 0);
  4394. hash = (hash * 397) ^ (this.z || 0);
  4395. hash = (hash * 397) ^ (this.w || 0);
  4396. return hash;
  4397. };
  4398. /**
  4399. * Copy the quaternion to an array
  4400. * @returns a new array populated with 4 elements from the quaternion coordinates
  4401. */
  4402. Quaternion.prototype.asArray = function () {
  4403. return [this.x, this.y, this.z, this.w];
  4404. };
  4405. /**
  4406. * Check if two quaternions are equals
  4407. * @param otherQuaternion defines the second operand
  4408. * @return true if the current quaternion and the given one coordinates are strictly equals
  4409. */
  4410. Quaternion.prototype.equals = function (otherQuaternion) {
  4411. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4412. };
  4413. /**
  4414. * Clone the current quaternion
  4415. * @returns a new quaternion copied from the current one
  4416. */
  4417. Quaternion.prototype.clone = function () {
  4418. return new Quaternion(this.x, this.y, this.z, this.w);
  4419. };
  4420. /**
  4421. * Copy a quaternion to the current one
  4422. * @param other defines the other quaternion
  4423. * @returns the updated current quaternion
  4424. */
  4425. Quaternion.prototype.copyFrom = function (other) {
  4426. this.x = other.x;
  4427. this.y = other.y;
  4428. this.z = other.z;
  4429. this.w = other.w;
  4430. return this;
  4431. };
  4432. /**
  4433. * Updates the current quaternion with the given float coordinates
  4434. * @param x defines the x coordinate
  4435. * @param y defines the y coordinate
  4436. * @param z defines the z coordinate
  4437. * @param w defines the w coordinate
  4438. * @returns the updated current quaternion
  4439. */
  4440. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4441. this.x = x;
  4442. this.y = y;
  4443. this.z = z;
  4444. this.w = w;
  4445. return this;
  4446. };
  4447. /**
  4448. * Updates the current quaternion from the given float coordinates
  4449. * @param x defines the x coordinate
  4450. * @param y defines the y coordinate
  4451. * @param z defines the z coordinate
  4452. * @param w defines the w coordinate
  4453. * @returns the updated current quaternion
  4454. */
  4455. Quaternion.prototype.set = function (x, y, z, w) {
  4456. return this.copyFromFloats(x, y, z, w);
  4457. };
  4458. /**
  4459. * Adds two quaternions
  4460. * @param other defines the second operand
  4461. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4462. */
  4463. Quaternion.prototype.add = function (other) {
  4464. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4465. };
  4466. /**
  4467. * Add a quaternion to the current one
  4468. * @param other defines the quaternion to add
  4469. * @returns the current quaternion
  4470. */
  4471. Quaternion.prototype.addInPlace = function (other) {
  4472. this.x += other.x;
  4473. this.y += other.y;
  4474. this.z += other.z;
  4475. this.w += other.w;
  4476. return this;
  4477. };
  4478. /**
  4479. * Subtract two quaternions
  4480. * @param other defines the second operand
  4481. * @returns a new quaternion as the subtraction result of the given one from the current one
  4482. */
  4483. Quaternion.prototype.subtract = function (other) {
  4484. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4485. };
  4486. /**
  4487. * Multiplies the current quaternion by a scale factor
  4488. * @param value defines the scale factor
  4489. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4490. */
  4491. Quaternion.prototype.scale = function (value) {
  4492. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4493. };
  4494. /**
  4495. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4496. * @param scale defines the scale factor
  4497. * @param result defines the Quaternion object where to store the result
  4498. * @returns the unmodified current quaternion
  4499. */
  4500. Quaternion.prototype.scaleToRef = function (scale, result) {
  4501. result.x = this.x * scale;
  4502. result.y = this.y * scale;
  4503. result.z = this.z * scale;
  4504. result.w = this.w * scale;
  4505. return this;
  4506. };
  4507. /**
  4508. * Multiplies in place the current quaternion by a scale factor
  4509. * @param value defines the scale factor
  4510. * @returns the current modified quaternion
  4511. */
  4512. Quaternion.prototype.scaleInPlace = function (value) {
  4513. this.x *= value;
  4514. this.y *= value;
  4515. this.z *= value;
  4516. this.w *= value;
  4517. return this;
  4518. };
  4519. /**
  4520. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4521. * @param scale defines the scale factor
  4522. * @param result defines the Quaternion object where to store the result
  4523. * @returns the unmodified current quaternion
  4524. */
  4525. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4526. result.x += this.x * scale;
  4527. result.y += this.y * scale;
  4528. result.z += this.z * scale;
  4529. result.w += this.w * scale;
  4530. return this;
  4531. };
  4532. /**
  4533. * Multiplies two quaternions
  4534. * @param q1 defines the second operand
  4535. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4536. */
  4537. Quaternion.prototype.multiply = function (q1) {
  4538. var result = new Quaternion(0, 0, 0, 1.0);
  4539. this.multiplyToRef(q1, result);
  4540. return result;
  4541. };
  4542. /**
  4543. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4544. * @param q1 defines the second operand
  4545. * @param result defines the target quaternion
  4546. * @returns the current quaternion
  4547. */
  4548. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4549. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4550. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4551. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4552. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4553. result.copyFromFloats(x, y, z, w);
  4554. return this;
  4555. };
  4556. /**
  4557. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4558. * @param q1 defines the second operand
  4559. * @returns the currentupdated quaternion
  4560. */
  4561. Quaternion.prototype.multiplyInPlace = function (q1) {
  4562. this.multiplyToRef(q1, this);
  4563. return this;
  4564. };
  4565. /**
  4566. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4567. * @param ref defines the target quaternion
  4568. * @returns the current quaternion
  4569. */
  4570. Quaternion.prototype.conjugateToRef = function (ref) {
  4571. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4572. return this;
  4573. };
  4574. /**
  4575. * Conjugates in place (1-q) the current quaternion
  4576. * @returns the current updated quaternion
  4577. */
  4578. Quaternion.prototype.conjugateInPlace = function () {
  4579. this.x *= -1;
  4580. this.y *= -1;
  4581. this.z *= -1;
  4582. return this;
  4583. };
  4584. /**
  4585. * Conjugates in place (1-q) the current quaternion
  4586. * @returns a new quaternion
  4587. */
  4588. Quaternion.prototype.conjugate = function () {
  4589. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4590. return result;
  4591. };
  4592. /**
  4593. * Gets length of current quaternion
  4594. * @returns the quaternion length (float)
  4595. */
  4596. Quaternion.prototype.length = function () {
  4597. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4598. };
  4599. /**
  4600. * Normalize in place the current quaternion
  4601. * @returns the current updated quaternion
  4602. */
  4603. Quaternion.prototype.normalize = function () {
  4604. var length = 1.0 / this.length();
  4605. this.x *= length;
  4606. this.y *= length;
  4607. this.z *= length;
  4608. this.w *= length;
  4609. return this;
  4610. };
  4611. /**
  4612. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4613. * @param order is a reserved parameter and is ignore for now
  4614. * @returns a new Vector3 containing the Euler angles
  4615. */
  4616. Quaternion.prototype.toEulerAngles = function (order) {
  4617. if (order === void 0) { order = "YZX"; }
  4618. var result = Vector3.Zero();
  4619. this.toEulerAnglesToRef(result, order);
  4620. return result;
  4621. };
  4622. /**
  4623. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4624. * @param result defines the vector which will be filled with the Euler angles
  4625. * @param order is a reserved parameter and is ignore for now
  4626. * @returns the current unchanged quaternion
  4627. */
  4628. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4629. if (order === void 0) { order = "YZX"; }
  4630. var qz = this.z;
  4631. var qx = this.x;
  4632. var qy = this.y;
  4633. var qw = this.w;
  4634. var sqw = qw * qw;
  4635. var sqz = qz * qz;
  4636. var sqx = qx * qx;
  4637. var sqy = qy * qy;
  4638. var zAxisY = qy * qz - qx * qw;
  4639. var limit = .4999999;
  4640. if (zAxisY < -limit) {
  4641. result.y = 2 * Math.atan2(qy, qw);
  4642. result.x = Math.PI / 2;
  4643. result.z = 0;
  4644. }
  4645. else if (zAxisY > limit) {
  4646. result.y = 2 * Math.atan2(qy, qw);
  4647. result.x = -Math.PI / 2;
  4648. result.z = 0;
  4649. }
  4650. else {
  4651. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4652. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4653. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4654. }
  4655. return this;
  4656. };
  4657. /**
  4658. * Updates the given rotation matrix with the current quaternion values
  4659. * @param result defines the target matrix
  4660. * @returns the current unchanged quaternion
  4661. */
  4662. Quaternion.prototype.toRotationMatrix = function (result) {
  4663. var xx = this.x * this.x;
  4664. var yy = this.y * this.y;
  4665. var zz = this.z * this.z;
  4666. var xy = this.x * this.y;
  4667. var zw = this.z * this.w;
  4668. var zx = this.z * this.x;
  4669. var yw = this.y * this.w;
  4670. var yz = this.y * this.z;
  4671. var xw = this.x * this.w;
  4672. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4673. result.m[1] = 2.0 * (xy + zw);
  4674. result.m[2] = 2.0 * (zx - yw);
  4675. result.m[3] = 0;
  4676. result.m[4] = 2.0 * (xy - zw);
  4677. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4678. result.m[6] = 2.0 * (yz + xw);
  4679. result.m[7] = 0;
  4680. result.m[8] = 2.0 * (zx + yw);
  4681. result.m[9] = 2.0 * (yz - xw);
  4682. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4683. result.m[11] = 0;
  4684. result.m[12] = 0;
  4685. result.m[13] = 0;
  4686. result.m[14] = 0;
  4687. result.m[15] = 1.0;
  4688. result._markAsUpdated();
  4689. return this;
  4690. };
  4691. /**
  4692. * Updates the current quaternion from the given rotation matrix values
  4693. * @param matrix defines the source matrix
  4694. * @returns the current updated quaternion
  4695. */
  4696. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4697. Quaternion.FromRotationMatrixToRef(matrix, this);
  4698. return this;
  4699. };
  4700. // Statics
  4701. /**
  4702. * Creates a new quaternion from a rotation matrix
  4703. * @param matrix defines the source matrix
  4704. * @returns a new quaternion created from the given rotation matrix values
  4705. */
  4706. Quaternion.FromRotationMatrix = function (matrix) {
  4707. var result = new Quaternion();
  4708. Quaternion.FromRotationMatrixToRef(matrix, result);
  4709. return result;
  4710. };
  4711. /**
  4712. * Updates the given quaternion with the given rotation matrix values
  4713. * @param matrix defines the source matrix
  4714. * @param result defines the target quaternion
  4715. */
  4716. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4717. var data = matrix.m;
  4718. var m11 = data[0], m12 = data[4], m13 = data[8];
  4719. var m21 = data[1], m22 = data[5], m23 = data[9];
  4720. var m31 = data[2], m32 = data[6], m33 = data[10];
  4721. var trace = m11 + m22 + m33;
  4722. var s;
  4723. if (trace > 0) {
  4724. s = 0.5 / Math.sqrt(trace + 1.0);
  4725. result.w = 0.25 / s;
  4726. result.x = (m32 - m23) * s;
  4727. result.y = (m13 - m31) * s;
  4728. result.z = (m21 - m12) * s;
  4729. }
  4730. else if (m11 > m22 && m11 > m33) {
  4731. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4732. result.w = (m32 - m23) / s;
  4733. result.x = 0.25 * s;
  4734. result.y = (m12 + m21) / s;
  4735. result.z = (m13 + m31) / s;
  4736. }
  4737. else if (m22 > m33) {
  4738. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4739. result.w = (m13 - m31) / s;
  4740. result.x = (m12 + m21) / s;
  4741. result.y = 0.25 * s;
  4742. result.z = (m23 + m32) / s;
  4743. }
  4744. else {
  4745. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4746. result.w = (m21 - m12) / s;
  4747. result.x = (m13 + m31) / s;
  4748. result.y = (m23 + m32) / s;
  4749. result.z = 0.25 * s;
  4750. }
  4751. };
  4752. /**
  4753. * Creates an empty quaternion
  4754. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4755. */
  4756. Quaternion.Zero = function () {
  4757. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4758. };
  4759. /**
  4760. * Inverse a given quaternion
  4761. * @param q defines the source quaternion
  4762. * @returns a new quaternion as the inverted current quaternion
  4763. */
  4764. Quaternion.Inverse = function (q) {
  4765. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4766. };
  4767. /**
  4768. * Creates an identity quaternion
  4769. * @returns the identity quaternion
  4770. */
  4771. Quaternion.Identity = function () {
  4772. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4773. };
  4774. /**
  4775. * Gets a boolean indicating if the given quaternion is identity
  4776. * @param quaternion defines the quaternion to check
  4777. * @returns true if the quaternion is identity
  4778. */
  4779. Quaternion.IsIdentity = function (quaternion) {
  4780. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4781. };
  4782. /**
  4783. * Creates a quaternion from a rotation around an axis
  4784. * @param axis defines the axis to use
  4785. * @param angle defines the angle to use
  4786. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4787. */
  4788. Quaternion.RotationAxis = function (axis, angle) {
  4789. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4790. };
  4791. /**
  4792. * Creates a rotation around an axis and stores it into the given quaternion
  4793. * @param axis defines the axis to use
  4794. * @param angle defines the angle to use
  4795. * @param result defines the target quaternion
  4796. * @returns the target quaternion
  4797. */
  4798. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4799. var sin = Math.sin(angle / 2);
  4800. axis.normalize();
  4801. result.w = Math.cos(angle / 2);
  4802. result.x = axis.x * sin;
  4803. result.y = axis.y * sin;
  4804. result.z = axis.z * sin;
  4805. return result;
  4806. };
  4807. /**
  4808. * Creates a new quaternion from data stored into an array
  4809. * @param array defines the data source
  4810. * @param offset defines the offset in the source array where the data starts
  4811. * @returns a new quaternion
  4812. */
  4813. Quaternion.FromArray = function (array, offset) {
  4814. if (!offset) {
  4815. offset = 0;
  4816. }
  4817. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4818. };
  4819. /**
  4820. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4821. * @param yaw defines the rotation around Y axis
  4822. * @param pitch defines the rotation around X axis
  4823. * @param roll defines the rotation around Z axis
  4824. * @returns the new quaternion
  4825. */
  4826. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4827. var q = new Quaternion();
  4828. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4829. return q;
  4830. };
  4831. /**
  4832. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4833. * @param yaw defines the rotation around Y axis
  4834. * @param pitch defines the rotation around X axis
  4835. * @param roll defines the rotation around Z axis
  4836. * @param result defines the target quaternion
  4837. */
  4838. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4839. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4840. var halfRoll = roll * 0.5;
  4841. var halfPitch = pitch * 0.5;
  4842. var halfYaw = yaw * 0.5;
  4843. var sinRoll = Math.sin(halfRoll);
  4844. var cosRoll = Math.cos(halfRoll);
  4845. var sinPitch = Math.sin(halfPitch);
  4846. var cosPitch = Math.cos(halfPitch);
  4847. var sinYaw = Math.sin(halfYaw);
  4848. var cosYaw = Math.cos(halfYaw);
  4849. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4850. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4851. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4852. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4853. };
  4854. /**
  4855. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4856. * @param alpha defines the rotation around first axis
  4857. * @param beta defines the rotation around second axis
  4858. * @param gamma defines the rotation around third axis
  4859. * @returns the new quaternion
  4860. */
  4861. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4862. var result = new Quaternion();
  4863. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4864. return result;
  4865. };
  4866. /**
  4867. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4868. * @param alpha defines the rotation around first axis
  4869. * @param beta defines the rotation around second axis
  4870. * @param gamma defines the rotation around third axis
  4871. * @param result defines the target quaternion
  4872. */
  4873. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4874. // Produces a quaternion from Euler angles in the z-x-z orientation
  4875. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4876. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4877. var halfBeta = beta * 0.5;
  4878. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4879. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4880. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4881. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4882. };
  4883. /**
  4884. * 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)
  4885. * @param axis1 defines the first axis
  4886. * @param axis2 defines the second axis
  4887. * @param axis3 defines the third axis
  4888. * @returns the new quaternion
  4889. */
  4890. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4891. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4892. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4893. return quat;
  4894. };
  4895. /**
  4896. * 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
  4897. * @param axis1 defines the first axis
  4898. * @param axis2 defines the second axis
  4899. * @param axis3 defines the third axis
  4900. * @param ref defines the target quaternion
  4901. */
  4902. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4903. var rotMat = MathTmp.Matrix[0];
  4904. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4905. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4906. };
  4907. /**
  4908. * Interpolates between two quaternions
  4909. * @param left defines first quaternion
  4910. * @param right defines second quaternion
  4911. * @param amount defines the gradient to use
  4912. * @returns the new interpolated quaternion
  4913. */
  4914. Quaternion.Slerp = function (left, right, amount) {
  4915. var result = Quaternion.Identity();
  4916. Quaternion.SlerpToRef(left, right, amount, result);
  4917. return result;
  4918. };
  4919. /**
  4920. * Interpolates between two quaternions and stores it into a target quaternion
  4921. * @param left defines first quaternion
  4922. * @param right defines second quaternion
  4923. * @param amount defines the gradient to use
  4924. * @param result defines the target quaternion
  4925. */
  4926. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4927. var num2;
  4928. var num3;
  4929. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4930. var flag = false;
  4931. if (num4 < 0) {
  4932. flag = true;
  4933. num4 = -num4;
  4934. }
  4935. if (num4 > 0.999999) {
  4936. num3 = 1 - amount;
  4937. num2 = flag ? -amount : amount;
  4938. }
  4939. else {
  4940. var num5 = Math.acos(num4);
  4941. var num6 = (1.0 / Math.sin(num5));
  4942. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4943. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4944. }
  4945. result.x = (num3 * left.x) + (num2 * right.x);
  4946. result.y = (num3 * left.y) + (num2 * right.y);
  4947. result.z = (num3 * left.z) + (num2 * right.z);
  4948. result.w = (num3 * left.w) + (num2 * right.w);
  4949. };
  4950. /**
  4951. * Interpolate between two quaternions using Hermite interpolation
  4952. * @param value1 defines first quaternion
  4953. * @param tangent1 defines the incoming tangent
  4954. * @param value2 defines second quaternion
  4955. * @param tangent2 defines the outgoing tangent
  4956. * @param amount defines the target quaternion
  4957. * @returns the new interpolated quaternion
  4958. */
  4959. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4960. var squared = amount * amount;
  4961. var cubed = amount * squared;
  4962. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4963. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4964. var part3 = (cubed - (2.0 * squared)) + amount;
  4965. var part4 = cubed - squared;
  4966. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4967. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4968. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4969. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4970. return new Quaternion(x, y, z, w);
  4971. };
  4972. return Quaternion;
  4973. }());
  4974. BABYLON.Quaternion = Quaternion;
  4975. /**
  4976. * Class used to store matrix data (4x4)
  4977. */
  4978. var Matrix = /** @class */ (function () {
  4979. /**
  4980. * Creates an empty matrix (filled with zeros)
  4981. */
  4982. function Matrix() {
  4983. this._isIdentity = false;
  4984. this._isIdentityDirty = true;
  4985. /**
  4986. * Gets or sets the internal data of the matrix
  4987. */
  4988. this.m = new Float32Array(16);
  4989. this._markAsUpdated();
  4990. }
  4991. /** @hidden */
  4992. Matrix.prototype._markAsUpdated = function () {
  4993. this.updateFlag = Matrix._updateFlagSeed++;
  4994. this._isIdentityDirty = true;
  4995. };
  4996. // Properties
  4997. /**
  4998. * Check if the current matrix is indentity
  4999. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5000. * @returns true is the matrix is the identity matrix
  5001. */
  5002. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5003. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5004. if (this._isIdentityDirty) {
  5005. this._isIdentityDirty = false;
  5006. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5007. this._isIdentity = false;
  5008. }
  5009. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5010. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5011. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5012. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5013. this._isIdentity = false;
  5014. }
  5015. else {
  5016. this._isIdentity = true;
  5017. }
  5018. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5019. this._isIdentity = false;
  5020. }
  5021. }
  5022. return this._isIdentity;
  5023. };
  5024. /**
  5025. * Gets the determinant of the matrix
  5026. * @returns the matrix determinant
  5027. */
  5028. Matrix.prototype.determinant = function () {
  5029. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5030. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5031. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5032. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5033. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5034. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5035. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5036. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5037. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5038. };
  5039. // Methods
  5040. /**
  5041. * Returns the matrix as a Float32Array
  5042. * @returns the matrix underlying array
  5043. */
  5044. Matrix.prototype.toArray = function () {
  5045. return this.m;
  5046. };
  5047. /**
  5048. * Returns the matrix as a Float32Array
  5049. * @returns the matrix underlying array.
  5050. */
  5051. Matrix.prototype.asArray = function () {
  5052. return this.toArray();
  5053. };
  5054. /**
  5055. * Inverts the current matrix in place
  5056. * @returns the current inverted matrix
  5057. */
  5058. Matrix.prototype.invert = function () {
  5059. this.invertToRef(this);
  5060. return this;
  5061. };
  5062. /**
  5063. * Sets all the matrix elements to zero
  5064. * @returns the current matrix
  5065. */
  5066. Matrix.prototype.reset = function () {
  5067. for (var index = 0; index < 16; index++) {
  5068. this.m[index] = 0.0;
  5069. }
  5070. this._markAsUpdated();
  5071. return this;
  5072. };
  5073. /**
  5074. * Adds the current matrix with a second one
  5075. * @param other defines the matrix to add
  5076. * @returns a new matrix as the addition of the current matrix and the given one
  5077. */
  5078. Matrix.prototype.add = function (other) {
  5079. var result = new Matrix();
  5080. this.addToRef(other, result);
  5081. return result;
  5082. };
  5083. /**
  5084. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5085. * @param other defines the matrix to add
  5086. * @param result defines the target matrix
  5087. * @returns the current matrix
  5088. */
  5089. Matrix.prototype.addToRef = function (other, result) {
  5090. for (var index = 0; index < 16; index++) {
  5091. result.m[index] = this.m[index] + other.m[index];
  5092. }
  5093. result._markAsUpdated();
  5094. return this;
  5095. };
  5096. /**
  5097. * Adds in place the given matrix to the current matrix
  5098. * @param other defines the second operand
  5099. * @returns the current updated matrix
  5100. */
  5101. Matrix.prototype.addToSelf = function (other) {
  5102. for (var index = 0; index < 16; index++) {
  5103. this.m[index] += other.m[index];
  5104. }
  5105. this._markAsUpdated();
  5106. return this;
  5107. };
  5108. /**
  5109. * Sets the given matrix to the current inverted Matrix
  5110. * @param other defines the target matrix
  5111. * @returns the unmodified current matrix
  5112. */
  5113. Matrix.prototype.invertToRef = function (other) {
  5114. var l1 = this.m[0];
  5115. var l2 = this.m[1];
  5116. var l3 = this.m[2];
  5117. var l4 = this.m[3];
  5118. var l5 = this.m[4];
  5119. var l6 = this.m[5];
  5120. var l7 = this.m[6];
  5121. var l8 = this.m[7];
  5122. var l9 = this.m[8];
  5123. var l10 = this.m[9];
  5124. var l11 = this.m[10];
  5125. var l12 = this.m[11];
  5126. var l13 = this.m[12];
  5127. var l14 = this.m[13];
  5128. var l15 = this.m[14];
  5129. var l16 = this.m[15];
  5130. var l17 = (l11 * l16) - (l12 * l15);
  5131. var l18 = (l10 * l16) - (l12 * l14);
  5132. var l19 = (l10 * l15) - (l11 * l14);
  5133. var l20 = (l9 * l16) - (l12 * l13);
  5134. var l21 = (l9 * l15) - (l11 * l13);
  5135. var l22 = (l9 * l14) - (l10 * l13);
  5136. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5137. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5138. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5139. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5140. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5141. var l28 = (l7 * l16) - (l8 * l15);
  5142. var l29 = (l6 * l16) - (l8 * l14);
  5143. var l30 = (l6 * l15) - (l7 * l14);
  5144. var l31 = (l5 * l16) - (l8 * l13);
  5145. var l32 = (l5 * l15) - (l7 * l13);
  5146. var l33 = (l5 * l14) - (l6 * l13);
  5147. var l34 = (l7 * l12) - (l8 * l11);
  5148. var l35 = (l6 * l12) - (l8 * l10);
  5149. var l36 = (l6 * l11) - (l7 * l10);
  5150. var l37 = (l5 * l12) - (l8 * l9);
  5151. var l38 = (l5 * l11) - (l7 * l9);
  5152. var l39 = (l5 * l10) - (l6 * l9);
  5153. other.m[0] = l23 * l27;
  5154. other.m[4] = l24 * l27;
  5155. other.m[8] = l25 * l27;
  5156. other.m[12] = l26 * l27;
  5157. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5158. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5159. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5160. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5161. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5162. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5163. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5164. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5165. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5166. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5167. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5168. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5169. other._markAsUpdated();
  5170. return this;
  5171. };
  5172. /**
  5173. * Inserts the translation vector (using 3 floats) in the current matrix
  5174. * @param x defines the 1st component of the translation
  5175. * @param y defines the 2nd component of the translation
  5176. * @param z defines the 3rd component of the translation
  5177. * @returns the current updated matrix
  5178. */
  5179. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5180. this.m[12] = x;
  5181. this.m[13] = y;
  5182. this.m[14] = z;
  5183. this._markAsUpdated();
  5184. return this;
  5185. };
  5186. /**
  5187. * Inserts the translation vector in the current matrix
  5188. * @param vector3 defines the translation to insert
  5189. * @returns the current updated matrix
  5190. */
  5191. Matrix.prototype.setTranslation = function (vector3) {
  5192. this.m[12] = vector3.x;
  5193. this.m[13] = vector3.y;
  5194. this.m[14] = vector3.z;
  5195. this._markAsUpdated();
  5196. return this;
  5197. };
  5198. /**
  5199. * Gets the translation value of the current matrix
  5200. * @returns a new Vector3 as the extracted translation from the matrix
  5201. */
  5202. Matrix.prototype.getTranslation = function () {
  5203. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5204. };
  5205. /**
  5206. * Fill a Vector3 with the extracted translation from the matrix
  5207. * @param result defines the Vector3 where to store the translation
  5208. * @returns the current matrix
  5209. */
  5210. Matrix.prototype.getTranslationToRef = function (result) {
  5211. result.x = this.m[12];
  5212. result.y = this.m[13];
  5213. result.z = this.m[14];
  5214. return this;
  5215. };
  5216. /**
  5217. * Remove rotation and scaling part from the matrix
  5218. * @returns the updated matrix
  5219. */
  5220. Matrix.prototype.removeRotationAndScaling = function () {
  5221. this.setRowFromFloats(0, 1, 0, 0, 0);
  5222. this.setRowFromFloats(1, 0, 1, 0, 0);
  5223. this.setRowFromFloats(2, 0, 0, 1, 0);
  5224. return this;
  5225. };
  5226. /**
  5227. * Multiply two matrices
  5228. * @param other defines the second operand
  5229. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5230. */
  5231. Matrix.prototype.multiply = function (other) {
  5232. var result = new Matrix();
  5233. this.multiplyToRef(other, result);
  5234. return result;
  5235. };
  5236. /**
  5237. * Copy the current matrix from the given one
  5238. * @param other defines the source matrix
  5239. * @returns the current updated matrix
  5240. */
  5241. Matrix.prototype.copyFrom = function (other) {
  5242. for (var index = 0; index < 16; index++) {
  5243. this.m[index] = other.m[index];
  5244. }
  5245. this._markAsUpdated();
  5246. return this;
  5247. };
  5248. /**
  5249. * Populates the given array from the starting index with the current matrix values
  5250. * @param array defines the target array
  5251. * @param offset defines the offset in the target array where to start storing values
  5252. * @returns the current matrix
  5253. */
  5254. Matrix.prototype.copyToArray = function (array, offset) {
  5255. if (offset === void 0) { offset = 0; }
  5256. for (var index = 0; index < 16; index++) {
  5257. array[offset + index] = this.m[index];
  5258. }
  5259. return this;
  5260. };
  5261. /**
  5262. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5263. * @param other defines the second operand
  5264. * @param result defines the matrix where to store the multiplication
  5265. * @returns the current matrix
  5266. */
  5267. Matrix.prototype.multiplyToRef = function (other, result) {
  5268. this.multiplyToArray(other, result.m, 0);
  5269. result._markAsUpdated();
  5270. return this;
  5271. };
  5272. /**
  5273. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5274. * @param other defines the second operand
  5275. * @param result defines the array where to store the multiplication
  5276. * @param offset defines the offset in the target array where to start storing values
  5277. * @returns the current matrix
  5278. */
  5279. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5280. var tm0 = this.m[0];
  5281. var tm1 = this.m[1];
  5282. var tm2 = this.m[2];
  5283. var tm3 = this.m[3];
  5284. var tm4 = this.m[4];
  5285. var tm5 = this.m[5];
  5286. var tm6 = this.m[6];
  5287. var tm7 = this.m[7];
  5288. var tm8 = this.m[8];
  5289. var tm9 = this.m[9];
  5290. var tm10 = this.m[10];
  5291. var tm11 = this.m[11];
  5292. var tm12 = this.m[12];
  5293. var tm13 = this.m[13];
  5294. var tm14 = this.m[14];
  5295. var tm15 = this.m[15];
  5296. var om0 = other.m[0];
  5297. var om1 = other.m[1];
  5298. var om2 = other.m[2];
  5299. var om3 = other.m[3];
  5300. var om4 = other.m[4];
  5301. var om5 = other.m[5];
  5302. var om6 = other.m[6];
  5303. var om7 = other.m[7];
  5304. var om8 = other.m[8];
  5305. var om9 = other.m[9];
  5306. var om10 = other.m[10];
  5307. var om11 = other.m[11];
  5308. var om12 = other.m[12];
  5309. var om13 = other.m[13];
  5310. var om14 = other.m[14];
  5311. var om15 = other.m[15];
  5312. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5313. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5314. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5315. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5316. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5317. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5318. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5319. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5320. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5321. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5322. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5323. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5324. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5325. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5326. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5327. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5328. return this;
  5329. };
  5330. /**
  5331. * Check equality between this matrix and a second one
  5332. * @param value defines the second matrix to compare
  5333. * @returns true is the current matrix and the given one values are strictly equal
  5334. */
  5335. Matrix.prototype.equals = function (value) {
  5336. return value &&
  5337. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5338. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5339. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5340. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5341. };
  5342. /**
  5343. * Clone the current matrix
  5344. * @returns a new matrix from the current matrix
  5345. */
  5346. Matrix.prototype.clone = function () {
  5347. 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]);
  5348. };
  5349. /**
  5350. * Returns the name of the current matrix class
  5351. * @returns the string "Matrix"
  5352. */
  5353. Matrix.prototype.getClassName = function () {
  5354. return "Matrix";
  5355. };
  5356. /**
  5357. * Gets the hash code of the current matrix
  5358. * @returns the hash code
  5359. */
  5360. Matrix.prototype.getHashCode = function () {
  5361. var hash = this.m[0] || 0;
  5362. for (var i = 1; i < 16; i++) {
  5363. hash = (hash * 397) ^ (this.m[i] || 0);
  5364. }
  5365. return hash;
  5366. };
  5367. /**
  5368. * Decomposes the current Matrix into a translation, rotation and scaling components
  5369. * @param scale defines the scale vector3 given as a reference to update
  5370. * @param rotation defines the rotation quaternion given as a reference to update
  5371. * @param translation defines the translation vector3 given as a reference to update
  5372. * @returns true if operation was successful
  5373. */
  5374. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5375. if (translation) {
  5376. translation.x = this.m[12];
  5377. translation.y = this.m[13];
  5378. translation.z = this.m[14];
  5379. }
  5380. scale = scale || MathTmp.Vector3[0];
  5381. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5382. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5383. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5384. if (this.determinant() <= 0) {
  5385. scale.y *= -1;
  5386. }
  5387. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5388. if (rotation) {
  5389. rotation.x = 0;
  5390. rotation.y = 0;
  5391. rotation.z = 0;
  5392. rotation.w = 1;
  5393. }
  5394. return false;
  5395. }
  5396. if (rotation) {
  5397. 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]);
  5398. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5399. }
  5400. return true;
  5401. };
  5402. /**
  5403. * Gets specific row of the matrix
  5404. * @param index defines the number of the row to get
  5405. * @returns the index-th row of the current matrix as a new Vector4
  5406. */
  5407. Matrix.prototype.getRow = function (index) {
  5408. if (index < 0 || index > 3) {
  5409. return null;
  5410. }
  5411. var i = index * 4;
  5412. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5413. };
  5414. /**
  5415. * Sets the index-th row of the current matrix to the vector4 values
  5416. * @param index defines the number of the row to set
  5417. * @param row defines the target vector4
  5418. * @returns the updated current matrix
  5419. */
  5420. Matrix.prototype.setRow = function (index, row) {
  5421. if (index < 0 || index > 3) {
  5422. return this;
  5423. }
  5424. var i = index * 4;
  5425. this.m[i + 0] = row.x;
  5426. this.m[i + 1] = row.y;
  5427. this.m[i + 2] = row.z;
  5428. this.m[i + 3] = row.w;
  5429. this._markAsUpdated();
  5430. return this;
  5431. };
  5432. /**
  5433. * Compute the transpose of the matrix
  5434. * @returns the new transposed matrix
  5435. */
  5436. Matrix.prototype.transpose = function () {
  5437. return Matrix.Transpose(this);
  5438. };
  5439. /**
  5440. * Compute the transpose of the matrix and store it in a given matrix
  5441. * @param result defines the target matrix
  5442. * @returns the current matrix
  5443. */
  5444. Matrix.prototype.transposeToRef = function (result) {
  5445. Matrix.TransposeToRef(this, result);
  5446. return this;
  5447. };
  5448. /**
  5449. * Sets the index-th row of the current matrix with the given 4 x float values
  5450. * @param index defines the row index
  5451. * @param x defines the x component to set
  5452. * @param y defines the y component to set
  5453. * @param z defines the z component to set
  5454. * @param w defines the w component to set
  5455. * @returns the updated current matrix
  5456. */
  5457. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5458. if (index < 0 || index > 3) {
  5459. return this;
  5460. }
  5461. var i = index * 4;
  5462. this.m[i + 0] = x;
  5463. this.m[i + 1] = y;
  5464. this.m[i + 2] = z;
  5465. this.m[i + 3] = w;
  5466. this._markAsUpdated();
  5467. return this;
  5468. };
  5469. /**
  5470. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5471. * @param scale defines the scale factor
  5472. * @returns a new matrix
  5473. */
  5474. Matrix.prototype.scale = function (scale) {
  5475. var result = new Matrix();
  5476. this.scaleToRef(scale, result);
  5477. return result;
  5478. };
  5479. /**
  5480. * Scale the current matrix values by a factor to a given result matrix
  5481. * @param scale defines the scale factor
  5482. * @param result defines the matrix to store the result
  5483. * @returns the current matrix
  5484. */
  5485. Matrix.prototype.scaleToRef = function (scale, result) {
  5486. for (var index = 0; index < 16; index++) {
  5487. result.m[index] = this.m[index] * scale;
  5488. }
  5489. result._markAsUpdated();
  5490. return this;
  5491. };
  5492. /**
  5493. * Scale the current matrix values by a factor and add the result to a given matrix
  5494. * @param scale defines the scale factor
  5495. * @param result defines the Matrix to store the result
  5496. * @returns the current matrix
  5497. */
  5498. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5499. for (var index = 0; index < 16; index++) {
  5500. result.m[index] += this.m[index] * scale;
  5501. }
  5502. result._markAsUpdated();
  5503. return this;
  5504. };
  5505. /**
  5506. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5507. * @param ref matrix to store the result
  5508. */
  5509. Matrix.prototype.toNormalMatrix = function (ref) {
  5510. this.invertToRef(ref);
  5511. ref.transpose();
  5512. var m = ref.m;
  5513. 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);
  5514. };
  5515. /**
  5516. * Gets only rotation part of the current matrix
  5517. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5518. */
  5519. Matrix.prototype.getRotationMatrix = function () {
  5520. var result = Matrix.Identity();
  5521. this.getRotationMatrixToRef(result);
  5522. return result;
  5523. };
  5524. /**
  5525. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5526. * @param result defines the target matrix to store data to
  5527. * @returns the current matrix
  5528. */
  5529. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5530. var m = this.m;
  5531. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5532. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5533. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5534. if (this.determinant() <= 0) {
  5535. sy *= -1;
  5536. }
  5537. if (sx === 0 || sy === 0 || sz === 0) {
  5538. Matrix.IdentityToRef(result);
  5539. }
  5540. else {
  5541. 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);
  5542. }
  5543. return this;
  5544. };
  5545. // Statics
  5546. /**
  5547. * Creates a matrix from an array
  5548. * @param array defines the source array
  5549. * @param offset defines an offset in the source array
  5550. * @returns a new Matrix set from the starting index of the given array
  5551. */
  5552. Matrix.FromArray = function (array, offset) {
  5553. var result = new Matrix();
  5554. if (!offset) {
  5555. offset = 0;
  5556. }
  5557. Matrix.FromArrayToRef(array, offset, result);
  5558. return result;
  5559. };
  5560. /**
  5561. * Copy the content of an array into a given matrix
  5562. * @param array defines the source array
  5563. * @param offset defines an offset in the source array
  5564. * @param result defines the target matrix
  5565. */
  5566. Matrix.FromArrayToRef = function (array, offset, result) {
  5567. for (var index = 0; index < 16; index++) {
  5568. result.m[index] = array[index + offset];
  5569. }
  5570. result._markAsUpdated();
  5571. };
  5572. /**
  5573. * Stores an array into a matrix after having multiplied each component by a given factor
  5574. * @param array defines the source array
  5575. * @param offset defines the offset in the source array
  5576. * @param scale defines the scaling factor
  5577. * @param result defines the target matrix
  5578. */
  5579. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5580. for (var index = 0; index < 16; index++) {
  5581. result.m[index] = array[index + offset] * scale;
  5582. }
  5583. result._markAsUpdated();
  5584. };
  5585. /**
  5586. * Stores a list of values (16) inside a given matrix
  5587. * @param initialM11 defines 1st value of 1st row
  5588. * @param initialM12 defines 2nd value of 1st row
  5589. * @param initialM13 defines 3rd value of 1st row
  5590. * @param initialM14 defines 4th value of 1st row
  5591. * @param initialM21 defines 1st value of 2nd row
  5592. * @param initialM22 defines 2nd value of 2nd row
  5593. * @param initialM23 defines 3rd value of 2nd row
  5594. * @param initialM24 defines 4th value of 2nd row
  5595. * @param initialM31 defines 1st value of 3rd row
  5596. * @param initialM32 defines 2nd value of 3rd row
  5597. * @param initialM33 defines 3rd value of 3rd row
  5598. * @param initialM34 defines 4th value of 3rd row
  5599. * @param initialM41 defines 1st value of 4th row
  5600. * @param initialM42 defines 2nd value of 4th row
  5601. * @param initialM43 defines 3rd value of 4th row
  5602. * @param initialM44 defines 4th value of 4th row
  5603. * @param result defines the target matrix
  5604. */
  5605. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5606. result.m[0] = initialM11;
  5607. result.m[1] = initialM12;
  5608. result.m[2] = initialM13;
  5609. result.m[3] = initialM14;
  5610. result.m[4] = initialM21;
  5611. result.m[5] = initialM22;
  5612. result.m[6] = initialM23;
  5613. result.m[7] = initialM24;
  5614. result.m[8] = initialM31;
  5615. result.m[9] = initialM32;
  5616. result.m[10] = initialM33;
  5617. result.m[11] = initialM34;
  5618. result.m[12] = initialM41;
  5619. result.m[13] = initialM42;
  5620. result.m[14] = initialM43;
  5621. result.m[15] = initialM44;
  5622. result._markAsUpdated();
  5623. };
  5624. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5625. /**
  5626. * Gets an identity matrix that must not be updated
  5627. */
  5628. get: function () {
  5629. return Matrix._identityReadOnly;
  5630. },
  5631. enumerable: true,
  5632. configurable: true
  5633. });
  5634. /**
  5635. * Creates new matrix from a list of values (16)
  5636. * @param initialM11 defines 1st value of 1st row
  5637. * @param initialM12 defines 2nd value of 1st row
  5638. * @param initialM13 defines 3rd value of 1st row
  5639. * @param initialM14 defines 4th value of 1st row
  5640. * @param initialM21 defines 1st value of 2nd row
  5641. * @param initialM22 defines 2nd value of 2nd row
  5642. * @param initialM23 defines 3rd value of 2nd row
  5643. * @param initialM24 defines 4th value of 2nd row
  5644. * @param initialM31 defines 1st value of 3rd row
  5645. * @param initialM32 defines 2nd value of 3rd row
  5646. * @param initialM33 defines 3rd value of 3rd row
  5647. * @param initialM34 defines 4th value of 3rd row
  5648. * @param initialM41 defines 1st value of 4th row
  5649. * @param initialM42 defines 2nd value of 4th row
  5650. * @param initialM43 defines 3rd value of 4th row
  5651. * @param initialM44 defines 4th value of 4th row
  5652. * @returns the new matrix
  5653. */
  5654. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5655. var result = new Matrix();
  5656. result.m[0] = initialM11;
  5657. result.m[1] = initialM12;
  5658. result.m[2] = initialM13;
  5659. result.m[3] = initialM14;
  5660. result.m[4] = initialM21;
  5661. result.m[5] = initialM22;
  5662. result.m[6] = initialM23;
  5663. result.m[7] = initialM24;
  5664. result.m[8] = initialM31;
  5665. result.m[9] = initialM32;
  5666. result.m[10] = initialM33;
  5667. result.m[11] = initialM34;
  5668. result.m[12] = initialM41;
  5669. result.m[13] = initialM42;
  5670. result.m[14] = initialM43;
  5671. result.m[15] = initialM44;
  5672. return result;
  5673. };
  5674. /**
  5675. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5676. * @param scale defines the scale vector3
  5677. * @param rotation defines the rotation quaternion
  5678. * @param translation defines the translation vector3
  5679. * @returns a new matrix
  5680. */
  5681. Matrix.Compose = function (scale, rotation, translation) {
  5682. var result = Matrix.Identity();
  5683. Matrix.ComposeToRef(scale, rotation, translation, result);
  5684. return result;
  5685. };
  5686. /**
  5687. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5688. * @param scale defines the scale vector3
  5689. * @param rotation defines the rotation quaternion
  5690. * @param translation defines the translation vector3
  5691. * @param result defines the target matrix
  5692. */
  5693. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5694. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5695. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5696. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5697. result.setTranslation(translation);
  5698. };
  5699. /**
  5700. * Creates a new identity matrix
  5701. * @returns a new identity matrix
  5702. */
  5703. Matrix.Identity = function () {
  5704. 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);
  5705. };
  5706. /**
  5707. * Creates a new identity matrix and stores the result in a given matrix
  5708. * @param result defines the target matrix
  5709. */
  5710. Matrix.IdentityToRef = function (result) {
  5711. 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);
  5712. };
  5713. /**
  5714. * Creates a new zero matrix
  5715. * @returns a new zero matrix
  5716. */
  5717. Matrix.Zero = function () {
  5718. 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);
  5719. };
  5720. /**
  5721. * Creates a new rotation matrix for "angle" radians around the X axis
  5722. * @param angle defines the angle (in radians) to use
  5723. * @return the new matrix
  5724. */
  5725. Matrix.RotationX = function (angle) {
  5726. var result = new Matrix();
  5727. Matrix.RotationXToRef(angle, result);
  5728. return result;
  5729. };
  5730. /**
  5731. * Creates a new matrix as the invert of a given matrix
  5732. * @param source defines the source matrix
  5733. * @returns the new matrix
  5734. */
  5735. Matrix.Invert = function (source) {
  5736. var result = new Matrix();
  5737. source.invertToRef(result);
  5738. return result;
  5739. };
  5740. /**
  5741. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5742. * @param angle defines the angle (in radians) to use
  5743. * @param result defines the target matrix
  5744. */
  5745. Matrix.RotationXToRef = function (angle, result) {
  5746. var s = Math.sin(angle);
  5747. var c = Math.cos(angle);
  5748. result.m[0] = 1.0;
  5749. result.m[15] = 1.0;
  5750. result.m[5] = c;
  5751. result.m[10] = c;
  5752. result.m[9] = -s;
  5753. result.m[6] = s;
  5754. result.m[1] = 0.0;
  5755. result.m[2] = 0.0;
  5756. result.m[3] = 0.0;
  5757. result.m[4] = 0.0;
  5758. result.m[7] = 0.0;
  5759. result.m[8] = 0.0;
  5760. result.m[11] = 0.0;
  5761. result.m[12] = 0.0;
  5762. result.m[13] = 0.0;
  5763. result.m[14] = 0.0;
  5764. result._markAsUpdated();
  5765. };
  5766. /**
  5767. * Creates a new rotation matrix for "angle" radians around the Y axis
  5768. * @param angle defines the angle (in radians) to use
  5769. * @return the new matrix
  5770. */
  5771. Matrix.RotationY = function (angle) {
  5772. var result = new Matrix();
  5773. Matrix.RotationYToRef(angle, result);
  5774. return result;
  5775. };
  5776. /**
  5777. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5778. * @param angle defines the angle (in radians) to use
  5779. * @param result defines the target matrix
  5780. */
  5781. Matrix.RotationYToRef = function (angle, result) {
  5782. var s = Math.sin(angle);
  5783. var c = Math.cos(angle);
  5784. result.m[5] = 1.0;
  5785. result.m[15] = 1.0;
  5786. result.m[0] = c;
  5787. result.m[2] = -s;
  5788. result.m[8] = s;
  5789. result.m[10] = c;
  5790. result.m[1] = 0.0;
  5791. result.m[3] = 0.0;
  5792. result.m[4] = 0.0;
  5793. result.m[6] = 0.0;
  5794. result.m[7] = 0.0;
  5795. result.m[9] = 0.0;
  5796. result.m[11] = 0.0;
  5797. result.m[12] = 0.0;
  5798. result.m[13] = 0.0;
  5799. result.m[14] = 0.0;
  5800. result._markAsUpdated();
  5801. };
  5802. /**
  5803. * Creates a new rotation matrix for "angle" radians around the Z axis
  5804. * @param angle defines the angle (in radians) to use
  5805. * @return the new matrix
  5806. */
  5807. Matrix.RotationZ = function (angle) {
  5808. var result = new Matrix();
  5809. Matrix.RotationZToRef(angle, result);
  5810. return result;
  5811. };
  5812. /**
  5813. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5814. * @param angle defines the angle (in radians) to use
  5815. * @param result defines the target matrix
  5816. */
  5817. Matrix.RotationZToRef = function (angle, result) {
  5818. var s = Math.sin(angle);
  5819. var c = Math.cos(angle);
  5820. result.m[10] = 1.0;
  5821. result.m[15] = 1.0;
  5822. result.m[0] = c;
  5823. result.m[1] = s;
  5824. result.m[4] = -s;
  5825. result.m[5] = c;
  5826. result.m[2] = 0.0;
  5827. result.m[3] = 0.0;
  5828. result.m[6] = 0.0;
  5829. result.m[7] = 0.0;
  5830. result.m[8] = 0.0;
  5831. result.m[9] = 0.0;
  5832. result.m[11] = 0.0;
  5833. result.m[12] = 0.0;
  5834. result.m[13] = 0.0;
  5835. result.m[14] = 0.0;
  5836. result._markAsUpdated();
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the given axis
  5840. * @param axis defines the axis to use
  5841. * @param angle defines the angle (in radians) to use
  5842. * @return the new matrix
  5843. */
  5844. Matrix.RotationAxis = function (axis, angle) {
  5845. var result = Matrix.Zero();
  5846. Matrix.RotationAxisToRef(axis, angle, result);
  5847. return result;
  5848. };
  5849. /**
  5850. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5851. * @param axis defines the axis to use
  5852. * @param angle defines the angle (in radians) to use
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5856. var s = Math.sin(-angle);
  5857. var c = Math.cos(-angle);
  5858. var c1 = 1 - c;
  5859. axis.normalize();
  5860. result.m[0] = (axis.x * axis.x) * c1 + c;
  5861. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5862. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5863. result.m[3] = 0.0;
  5864. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5865. result.m[5] = (axis.y * axis.y) * c1 + c;
  5866. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5867. result.m[7] = 0.0;
  5868. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5869. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5870. result.m[10] = (axis.z * axis.z) * c1 + c;
  5871. result.m[11] = 0.0;
  5872. result.m[15] = 1.0;
  5873. result._markAsUpdated();
  5874. };
  5875. /**
  5876. * Creates a rotation matrix
  5877. * @param yaw defines the yaw angle in radians (Y axis)
  5878. * @param pitch defines the pitch angle in radians (X axis)
  5879. * @param roll defines the roll angle in radians (X axis)
  5880. * @returns the new rotation matrix
  5881. */
  5882. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5883. var result = new Matrix();
  5884. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5885. return result;
  5886. };
  5887. /**
  5888. * Creates a rotation matrix and stores it in a given matrix
  5889. * @param yaw defines the yaw angle in radians (Y axis)
  5890. * @param pitch defines the pitch angle in radians (X axis)
  5891. * @param roll defines the roll angle in radians (X axis)
  5892. * @param result defines the target matrix
  5893. */
  5894. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5895. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5896. this._tempQuaternion.toRotationMatrix(result);
  5897. };
  5898. /**
  5899. * Creates a scaling matrix
  5900. * @param x defines the scale factor on X axis
  5901. * @param y defines the scale factor on Y axis
  5902. * @param z defines the scale factor on Z axis
  5903. * @returns the new matrix
  5904. */
  5905. Matrix.Scaling = function (x, y, z) {
  5906. var result = Matrix.Zero();
  5907. Matrix.ScalingToRef(x, y, z, result);
  5908. return result;
  5909. };
  5910. /**
  5911. * Creates a scaling matrix and stores it in a given matrix
  5912. * @param x defines the scale factor on X axis
  5913. * @param y defines the scale factor on Y axis
  5914. * @param z defines the scale factor on Z axis
  5915. * @param result defines the target matrix
  5916. */
  5917. Matrix.ScalingToRef = function (x, y, z, result) {
  5918. result.m[0] = x;
  5919. result.m[1] = 0.0;
  5920. result.m[2] = 0.0;
  5921. result.m[3] = 0.0;
  5922. result.m[4] = 0.0;
  5923. result.m[5] = y;
  5924. result.m[6] = 0.0;
  5925. result.m[7] = 0.0;
  5926. result.m[8] = 0.0;
  5927. result.m[9] = 0.0;
  5928. result.m[10] = z;
  5929. result.m[11] = 0.0;
  5930. result.m[12] = 0.0;
  5931. result.m[13] = 0.0;
  5932. result.m[14] = 0.0;
  5933. result.m[15] = 1.0;
  5934. result._markAsUpdated();
  5935. };
  5936. /**
  5937. * Creates a translation matrix
  5938. * @param x defines the translation on X axis
  5939. * @param y defines the translation on Y axis
  5940. * @param z defines the translationon Z axis
  5941. * @returns the new matrix
  5942. */
  5943. Matrix.Translation = function (x, y, z) {
  5944. var result = Matrix.Identity();
  5945. Matrix.TranslationToRef(x, y, z, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a translation matrix and stores it in a given matrix
  5950. * @param x defines the translation on X axis
  5951. * @param y defines the translation on Y axis
  5952. * @param z defines the translationon Z axis
  5953. * @param result defines the target matrix
  5954. */
  5955. Matrix.TranslationToRef = function (x, y, z, result) {
  5956. 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);
  5957. };
  5958. /**
  5959. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5960. * @param startValue defines the start value
  5961. * @param endValue defines the end value
  5962. * @param gradient defines the gradient factor
  5963. * @returns the new matrix
  5964. */
  5965. Matrix.Lerp = function (startValue, endValue, gradient) {
  5966. var result = Matrix.Zero();
  5967. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5968. return result;
  5969. };
  5970. /**
  5971. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5972. * @param startValue defines the start value
  5973. * @param endValue defines the end value
  5974. * @param gradient defines the gradient factor
  5975. * @param result defines the Matrix object where to store data
  5976. */
  5977. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5978. for (var index = 0; index < 16; index++) {
  5979. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5980. }
  5981. result._markAsUpdated();
  5982. };
  5983. /**
  5984. * Builds a new matrix whose values are computed by:
  5985. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5986. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5987. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5988. * @param startValue defines the first matrix
  5989. * @param endValue defines the second matrix
  5990. * @param gradient defines the gradient between the two matrices
  5991. * @returns the new matrix
  5992. */
  5993. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5994. var result = Matrix.Zero();
  5995. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5996. return result;
  5997. };
  5998. /**
  5999. * Update a matrix to values which are computed by:
  6000. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6001. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6002. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6003. * @param startValue defines the first matrix
  6004. * @param endValue defines the second matrix
  6005. * @param gradient defines the gradient between the two matrices
  6006. * @param result defines the target matrix
  6007. */
  6008. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6009. var startScale = MathTmp.Vector3[0];
  6010. var startRotation = MathTmp.Quaternion[0];
  6011. var startTranslation = MathTmp.Vector3[1];
  6012. startValue.decompose(startScale, startRotation, startTranslation);
  6013. var endScale = MathTmp.Vector3[2];
  6014. var endRotation = MathTmp.Quaternion[1];
  6015. var endTranslation = MathTmp.Vector3[3];
  6016. endValue.decompose(endScale, endRotation, endTranslation);
  6017. var resultScale = MathTmp.Vector3[4];
  6018. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6019. var resultRotation = MathTmp.Quaternion[2];
  6020. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6021. var resultTranslation = MathTmp.Vector3[5];
  6022. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6023. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6024. };
  6025. /**
  6026. * 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"
  6027. * This function works in left handed mode
  6028. * @param eye defines the final position of the entity
  6029. * @param target defines where the entity should look at
  6030. * @param up defines the up vector for the entity
  6031. * @returns the new matrix
  6032. */
  6033. Matrix.LookAtLH = function (eye, target, up) {
  6034. var result = Matrix.Zero();
  6035. Matrix.LookAtLHToRef(eye, target, up, result);
  6036. return result;
  6037. };
  6038. /**
  6039. * 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".
  6040. * This function works in left handed mode
  6041. * @param eye defines the final position of the entity
  6042. * @param target defines where the entity should look at
  6043. * @param up defines the up vector for the entity
  6044. * @param result defines the target matrix
  6045. */
  6046. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6047. // Z axis
  6048. target.subtractToRef(eye, this._zAxis);
  6049. this._zAxis.normalize();
  6050. // X axis
  6051. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6052. if (this._xAxis.lengthSquared() === 0) {
  6053. this._xAxis.x = 1.0;
  6054. }
  6055. else {
  6056. this._xAxis.normalize();
  6057. }
  6058. // Y axis
  6059. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6060. this._yAxis.normalize();
  6061. // Eye angles
  6062. var ex = -Vector3.Dot(this._xAxis, eye);
  6063. var ey = -Vector3.Dot(this._yAxis, eye);
  6064. var ez = -Vector3.Dot(this._zAxis, eye);
  6065. 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);
  6066. };
  6067. /**
  6068. * 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"
  6069. * This function works in right handed mode
  6070. * @param eye defines the final position of the entity
  6071. * @param target defines where the entity should look at
  6072. * @param up defines the up vector for the entity
  6073. * @returns the new matrix
  6074. */
  6075. Matrix.LookAtRH = function (eye, target, up) {
  6076. var result = Matrix.Zero();
  6077. Matrix.LookAtRHToRef(eye, target, up, result);
  6078. return result;
  6079. };
  6080. /**
  6081. * 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".
  6082. * This function works in right handed mode
  6083. * @param eye defines the final position of the entity
  6084. * @param target defines where the entity should look at
  6085. * @param up defines the up vector for the entity
  6086. * @param result defines the target matrix
  6087. */
  6088. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6089. // Z axis
  6090. eye.subtractToRef(target, this._zAxis);
  6091. this._zAxis.normalize();
  6092. // X axis
  6093. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6094. if (this._xAxis.lengthSquared() === 0) {
  6095. this._xAxis.x = 1.0;
  6096. }
  6097. else {
  6098. this._xAxis.normalize();
  6099. }
  6100. // Y axis
  6101. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6102. this._yAxis.normalize();
  6103. // Eye angles
  6104. var ex = -Vector3.Dot(this._xAxis, eye);
  6105. var ey = -Vector3.Dot(this._yAxis, eye);
  6106. var ez = -Vector3.Dot(this._zAxis, eye);
  6107. 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);
  6108. };
  6109. /**
  6110. * Create a left-handed orthographic projection matrix
  6111. * @param width defines the viewport width
  6112. * @param height defines the viewport height
  6113. * @param znear defines the near clip plane
  6114. * @param zfar defines the far clip plane
  6115. * @returns a new matrix as a left-handed orthographic projection matrix
  6116. */
  6117. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6118. var matrix = Matrix.Zero();
  6119. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6120. return matrix;
  6121. };
  6122. /**
  6123. * Store a left-handed orthographic projection to a given matrix
  6124. * @param width defines the viewport width
  6125. * @param height defines the viewport height
  6126. * @param znear defines the near clip plane
  6127. * @param zfar defines the far clip plane
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6131. var n = znear;
  6132. var f = zfar;
  6133. var a = 2.0 / width;
  6134. var b = 2.0 / height;
  6135. var c = 2.0 / (f - n);
  6136. var d = -(f + n) / (f - n);
  6137. 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);
  6138. };
  6139. /**
  6140. * Create a left-handed orthographic projection matrix
  6141. * @param left defines the viewport left coordinate
  6142. * @param right defines the viewport right coordinate
  6143. * @param bottom defines the viewport bottom coordinate
  6144. * @param top defines the viewport top coordinate
  6145. * @param znear defines the near clip plane
  6146. * @param zfar defines the far clip plane
  6147. * @returns a new matrix as a left-handed orthographic projection matrix
  6148. */
  6149. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6150. var matrix = Matrix.Zero();
  6151. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6152. return matrix;
  6153. };
  6154. /**
  6155. * Stores a left-handed orthographic projection into a given matrix
  6156. * @param left defines the viewport left coordinate
  6157. * @param right defines the viewport right coordinate
  6158. * @param bottom defines the viewport bottom coordinate
  6159. * @param top defines the viewport top coordinate
  6160. * @param znear defines the near clip plane
  6161. * @param zfar defines the far clip plane
  6162. * @param result defines the target matrix
  6163. */
  6164. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6165. var n = znear;
  6166. var f = zfar;
  6167. var a = 2.0 / (right - left);
  6168. var b = 2.0 / (top - bottom);
  6169. var c = 2.0 / (f - n);
  6170. var d = -(f + n) / (f - n);
  6171. var i0 = (left + right) / (left - right);
  6172. var i1 = (top + bottom) / (bottom - top);
  6173. 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);
  6174. };
  6175. /**
  6176. * Creates a right-handed orthographic projection matrix
  6177. * @param left defines the viewport left coordinate
  6178. * @param right defines the viewport right coordinate
  6179. * @param bottom defines the viewport bottom coordinate
  6180. * @param top defines the viewport top coordinate
  6181. * @param znear defines the near clip plane
  6182. * @param zfar defines the far clip plane
  6183. * @returns a new matrix as a right-handed orthographic projection matrix
  6184. */
  6185. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6186. var matrix = Matrix.Zero();
  6187. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6188. return matrix;
  6189. };
  6190. /**
  6191. * Stores a right-handed orthographic projection into a given matrix
  6192. * @param left defines the viewport left coordinate
  6193. * @param right defines the viewport right coordinate
  6194. * @param bottom defines the viewport bottom coordinate
  6195. * @param top defines the viewport top coordinate
  6196. * @param znear defines the near clip plane
  6197. * @param zfar defines the far clip plane
  6198. * @param result defines the target matrix
  6199. */
  6200. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6201. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6202. result.m[10] *= -1.0;
  6203. };
  6204. /**
  6205. * Creates a left-handed perspective projection matrix
  6206. * @param width defines the viewport width
  6207. * @param height defines the viewport height
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a left-handed perspective projection matrix
  6211. */
  6212. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. var n = znear;
  6215. var f = zfar;
  6216. var a = 2.0 * n / width;
  6217. var b = 2.0 * n / height;
  6218. var c = (f + n) / (f - n);
  6219. var d = -2.0 * f * n / (f - n);
  6220. 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);
  6221. return matrix;
  6222. };
  6223. /**
  6224. * Creates a left-handed perspective projection matrix
  6225. * @param fov defines the horizontal field of view
  6226. * @param aspect defines the aspect ratio
  6227. * @param znear defines the near clip plane
  6228. * @param zfar defines the far clip plane
  6229. * @returns a new matrix as a left-handed perspective projection matrix
  6230. */
  6231. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6232. var matrix = Matrix.Zero();
  6233. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6234. return matrix;
  6235. };
  6236. /**
  6237. * Stores a left-handed perspective projection into a given matrix
  6238. * @param fov defines the horizontal field of view
  6239. * @param aspect defines the aspect ratio
  6240. * @param znear defines the near clip plane
  6241. * @param zfar defines the far clip plane
  6242. * @param result defines the target matrix
  6243. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6244. */
  6245. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6246. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6247. var n = znear;
  6248. var f = zfar;
  6249. var t = 1.0 / (Math.tan(fov * 0.5));
  6250. var a = isVerticalFovFixed ? (t / aspect) : t;
  6251. var b = isVerticalFovFixed ? t : (t * aspect);
  6252. var c = (f + n) / (f - n);
  6253. var d = -2.0 * f * n / (f - n);
  6254. 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);
  6255. };
  6256. /**
  6257. * Creates a right-handed perspective projection matrix
  6258. * @param fov defines the horizontal field of view
  6259. * @param aspect defines the aspect ratio
  6260. * @param znear defines the near clip plane
  6261. * @param zfar defines the far clip plane
  6262. * @returns a new matrix as a right-handed perspective projection matrix
  6263. */
  6264. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6265. var matrix = Matrix.Zero();
  6266. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6267. return matrix;
  6268. };
  6269. /**
  6270. * Stores a right-handed perspective projection into a given matrix
  6271. * @param fov defines the horizontal field of view
  6272. * @param aspect defines the aspect ratio
  6273. * @param znear defines the near clip plane
  6274. * @param zfar defines the far clip plane
  6275. * @param result defines the target matrix
  6276. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6277. */
  6278. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6279. //alternatively this could be expressed as:
  6280. // m = PerspectiveFovLHToRef
  6281. // m[10] *= -1.0;
  6282. // m[11] *= -1.0;
  6283. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6284. var n = znear;
  6285. var f = zfar;
  6286. var t = 1.0 / (Math.tan(fov * 0.5));
  6287. var a = isVerticalFovFixed ? (t / aspect) : t;
  6288. var b = isVerticalFovFixed ? t : (t * aspect);
  6289. var c = -(f + n) / (f - n);
  6290. var d = -2 * f * n / (f - n);
  6291. 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);
  6292. };
  6293. /**
  6294. * Stores a perspective projection for WebVR info a given matrix
  6295. * @param fov defines the field of view
  6296. * @param znear defines the near clip plane
  6297. * @param zfar defines the far clip plane
  6298. * @param result defines the target matrix
  6299. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6300. */
  6301. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6302. if (rightHanded === void 0) { rightHanded = false; }
  6303. var rightHandedFactor = rightHanded ? -1 : 1;
  6304. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6305. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6306. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6307. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6308. var xScale = 2.0 / (leftTan + rightTan);
  6309. var yScale = 2.0 / (upTan + downTan);
  6310. result.m[0] = xScale;
  6311. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6312. result.m[5] = yScale;
  6313. result.m[6] = result.m[7] = 0.0;
  6314. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6315. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6316. result.m[10] = -zfar / (znear - zfar);
  6317. result.m[11] = 1.0 * rightHandedFactor;
  6318. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6319. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6320. result._markAsUpdated();
  6321. };
  6322. /**
  6323. * Computes a complete transformation matrix
  6324. * @param viewport defines the viewport to use
  6325. * @param world defines the world matrix
  6326. * @param view defines the view matrix
  6327. * @param projection defines the projection matrix
  6328. * @param zmin defines the near clip plane
  6329. * @param zmax defines the far clip plane
  6330. * @returns the transformation matrix
  6331. */
  6332. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6333. var cw = viewport.width;
  6334. var ch = viewport.height;
  6335. var cx = viewport.x;
  6336. var cy = viewport.y;
  6337. 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);
  6338. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6339. };
  6340. /**
  6341. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6342. * @param matrix defines the matrix to use
  6343. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6344. */
  6345. Matrix.GetAsMatrix2x2 = function (matrix) {
  6346. return new Float32Array([
  6347. matrix.m[0], matrix.m[1],
  6348. matrix.m[4], matrix.m[5]
  6349. ]);
  6350. };
  6351. /**
  6352. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6353. * @param matrix defines the matrix to use
  6354. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6355. */
  6356. Matrix.GetAsMatrix3x3 = function (matrix) {
  6357. return new Float32Array([
  6358. matrix.m[0], matrix.m[1], matrix.m[2],
  6359. matrix.m[4], matrix.m[5], matrix.m[6],
  6360. matrix.m[8], matrix.m[9], matrix.m[10]
  6361. ]);
  6362. };
  6363. /**
  6364. * Compute the transpose of a given matrix
  6365. * @param matrix defines the matrix to transpose
  6366. * @returns the new matrix
  6367. */
  6368. Matrix.Transpose = function (matrix) {
  6369. var result = new Matrix();
  6370. Matrix.TransposeToRef(matrix, result);
  6371. return result;
  6372. };
  6373. /**
  6374. * Compute the transpose of a matrix and store it in a target matrix
  6375. * @param matrix defines the matrix to transpose
  6376. * @param result defines the target matrix
  6377. */
  6378. Matrix.TransposeToRef = function (matrix, result) {
  6379. result.m[0] = matrix.m[0];
  6380. result.m[1] = matrix.m[4];
  6381. result.m[2] = matrix.m[8];
  6382. result.m[3] = matrix.m[12];
  6383. result.m[4] = matrix.m[1];
  6384. result.m[5] = matrix.m[5];
  6385. result.m[6] = matrix.m[9];
  6386. result.m[7] = matrix.m[13];
  6387. result.m[8] = matrix.m[2];
  6388. result.m[9] = matrix.m[6];
  6389. result.m[10] = matrix.m[10];
  6390. result.m[11] = matrix.m[14];
  6391. result.m[12] = matrix.m[3];
  6392. result.m[13] = matrix.m[7];
  6393. result.m[14] = matrix.m[11];
  6394. result.m[15] = matrix.m[15];
  6395. };
  6396. /**
  6397. * Computes a reflection matrix from a plane
  6398. * @param plane defines the reflection plane
  6399. * @returns a new matrix
  6400. */
  6401. Matrix.Reflection = function (plane) {
  6402. var matrix = new Matrix();
  6403. Matrix.ReflectionToRef(plane, matrix);
  6404. return matrix;
  6405. };
  6406. /**
  6407. * Computes a reflection matrix from a plane
  6408. * @param plane defines the reflection plane
  6409. * @param result defines the target matrix
  6410. */
  6411. Matrix.ReflectionToRef = function (plane, result) {
  6412. plane.normalize();
  6413. var x = plane.normal.x;
  6414. var y = plane.normal.y;
  6415. var z = plane.normal.z;
  6416. var temp = -2 * x;
  6417. var temp2 = -2 * y;
  6418. var temp3 = -2 * z;
  6419. result.m[0] = (temp * x) + 1;
  6420. result.m[1] = temp2 * x;
  6421. result.m[2] = temp3 * x;
  6422. result.m[3] = 0.0;
  6423. result.m[4] = temp * y;
  6424. result.m[5] = (temp2 * y) + 1;
  6425. result.m[6] = temp3 * y;
  6426. result.m[7] = 0.0;
  6427. result.m[8] = temp * z;
  6428. result.m[9] = temp2 * z;
  6429. result.m[10] = (temp3 * z) + 1;
  6430. result.m[11] = 0.0;
  6431. result.m[12] = temp * plane.d;
  6432. result.m[13] = temp2 * plane.d;
  6433. result.m[14] = temp3 * plane.d;
  6434. result.m[15] = 1.0;
  6435. result._markAsUpdated();
  6436. };
  6437. /**
  6438. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6439. * @param xaxis defines the value of the 1st axis
  6440. * @param yaxis defines the value of the 2nd axis
  6441. * @param zaxis defines the value of the 3rd axis
  6442. * @param result defines the target matrix
  6443. */
  6444. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6445. result.m[0] = xaxis.x;
  6446. result.m[1] = xaxis.y;
  6447. result.m[2] = xaxis.z;
  6448. result.m[3] = 0.0;
  6449. result.m[4] = yaxis.x;
  6450. result.m[5] = yaxis.y;
  6451. result.m[6] = yaxis.z;
  6452. result.m[7] = 0.0;
  6453. result.m[8] = zaxis.x;
  6454. result.m[9] = zaxis.y;
  6455. result.m[10] = zaxis.z;
  6456. result.m[11] = 0.0;
  6457. result.m[12] = 0.0;
  6458. result.m[13] = 0.0;
  6459. result.m[14] = 0.0;
  6460. result.m[15] = 1.0;
  6461. result._markAsUpdated();
  6462. };
  6463. /**
  6464. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6465. * @param quat defines the quaternion to use
  6466. * @param result defines the target matrix
  6467. */
  6468. Matrix.FromQuaternionToRef = function (quat, result) {
  6469. var xx = quat.x * quat.x;
  6470. var yy = quat.y * quat.y;
  6471. var zz = quat.z * quat.z;
  6472. var xy = quat.x * quat.y;
  6473. var zw = quat.z * quat.w;
  6474. var zx = quat.z * quat.x;
  6475. var yw = quat.y * quat.w;
  6476. var yz = quat.y * quat.z;
  6477. var xw = quat.x * quat.w;
  6478. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6479. result.m[1] = 2.0 * (xy + zw);
  6480. result.m[2] = 2.0 * (zx - yw);
  6481. result.m[3] = 0.0;
  6482. result.m[4] = 2.0 * (xy - zw);
  6483. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6484. result.m[6] = 2.0 * (yz + xw);
  6485. result.m[7] = 0.0;
  6486. result.m[8] = 2.0 * (zx + yw);
  6487. result.m[9] = 2.0 * (yz - xw);
  6488. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6489. result.m[11] = 0.0;
  6490. result.m[12] = 0.0;
  6491. result.m[13] = 0.0;
  6492. result.m[14] = 0.0;
  6493. result.m[15] = 1.0;
  6494. result._markAsUpdated();
  6495. };
  6496. Matrix._tempQuaternion = new Quaternion();
  6497. Matrix._xAxis = Vector3.Zero();
  6498. Matrix._yAxis = Vector3.Zero();
  6499. Matrix._zAxis = Vector3.Zero();
  6500. Matrix._updateFlagSeed = 0;
  6501. Matrix._identityReadOnly = Matrix.Identity();
  6502. return Matrix;
  6503. }());
  6504. BABYLON.Matrix = Matrix;
  6505. var Plane = /** @class */ (function () {
  6506. /**
  6507. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6508. */
  6509. function Plane(a, b, c, d) {
  6510. this.normal = new Vector3(a, b, c);
  6511. this.d = d;
  6512. }
  6513. /**
  6514. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6515. */
  6516. Plane.prototype.asArray = function () {
  6517. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6518. };
  6519. // Methods
  6520. /**
  6521. * Returns a new plane copied from the current Plane.
  6522. */
  6523. Plane.prototype.clone = function () {
  6524. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6525. };
  6526. /**
  6527. * Returns the string "Plane".
  6528. */
  6529. Plane.prototype.getClassName = function () {
  6530. return "Plane";
  6531. };
  6532. /**
  6533. * Returns the Plane hash code.
  6534. */
  6535. Plane.prototype.getHashCode = function () {
  6536. var hash = this.normal.getHashCode();
  6537. hash = (hash * 397) ^ (this.d || 0);
  6538. return hash;
  6539. };
  6540. /**
  6541. * Normalize the current Plane in place.
  6542. * Returns the updated Plane.
  6543. */
  6544. Plane.prototype.normalize = function () {
  6545. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6546. var magnitude = 0.0;
  6547. if (norm !== 0) {
  6548. magnitude = 1.0 / norm;
  6549. }
  6550. this.normal.x *= magnitude;
  6551. this.normal.y *= magnitude;
  6552. this.normal.z *= magnitude;
  6553. this.d *= magnitude;
  6554. return this;
  6555. };
  6556. /**
  6557. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6558. */
  6559. Plane.prototype.transform = function (transformation) {
  6560. var transposedMatrix = Matrix.Transpose(transformation);
  6561. var x = this.normal.x;
  6562. var y = this.normal.y;
  6563. var z = this.normal.z;
  6564. var d = this.d;
  6565. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6566. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6567. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6568. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6569. return new Plane(normalX, normalY, normalZ, finalD);
  6570. };
  6571. /**
  6572. * Returns the dot product (float) of the point coordinates and the plane normal.
  6573. */
  6574. Plane.prototype.dotCoordinate = function (point) {
  6575. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6576. };
  6577. /**
  6578. * Updates the current Plane from the plane defined by the three given points.
  6579. * Returns the updated Plane.
  6580. */
  6581. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6582. var x1 = point2.x - point1.x;
  6583. var y1 = point2.y - point1.y;
  6584. var z1 = point2.z - point1.z;
  6585. var x2 = point3.x - point1.x;
  6586. var y2 = point3.y - point1.y;
  6587. var z2 = point3.z - point1.z;
  6588. var yz = (y1 * z2) - (z1 * y2);
  6589. var xz = (z1 * x2) - (x1 * z2);
  6590. var xy = (x1 * y2) - (y1 * x2);
  6591. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6592. var invPyth;
  6593. if (pyth !== 0) {
  6594. invPyth = 1.0 / pyth;
  6595. }
  6596. else {
  6597. invPyth = 0.0;
  6598. }
  6599. this.normal.x = yz * invPyth;
  6600. this.normal.y = xz * invPyth;
  6601. this.normal.z = xy * invPyth;
  6602. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6603. return this;
  6604. };
  6605. /**
  6606. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6607. */
  6608. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6609. var dot = Vector3.Dot(this.normal, direction);
  6610. return (dot <= epsilon);
  6611. };
  6612. /**
  6613. * Returns the signed distance (float) from the given point to the Plane.
  6614. */
  6615. Plane.prototype.signedDistanceTo = function (point) {
  6616. return Vector3.Dot(point, this.normal) + this.d;
  6617. };
  6618. // Statics
  6619. /**
  6620. * Returns a new Plane from the given array.
  6621. */
  6622. Plane.FromArray = function (array) {
  6623. return new Plane(array[0], array[1], array[2], array[3]);
  6624. };
  6625. /**
  6626. * Returns a new Plane defined by the three given points.
  6627. */
  6628. Plane.FromPoints = function (point1, point2, point3) {
  6629. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6630. result.copyFromPoints(point1, point2, point3);
  6631. return result;
  6632. };
  6633. /**
  6634. * Returns a new Plane the normal vector to this plane at the given origin point.
  6635. * Note : the vector "normal" is updated because normalized.
  6636. */
  6637. Plane.FromPositionAndNormal = function (origin, normal) {
  6638. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6639. normal.normalize();
  6640. result.normal = normal;
  6641. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6642. return result;
  6643. };
  6644. /**
  6645. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6646. */
  6647. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6648. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6649. return Vector3.Dot(point, normal) + d;
  6650. };
  6651. return Plane;
  6652. }());
  6653. BABYLON.Plane = Plane;
  6654. var Viewport = /** @class */ (function () {
  6655. /**
  6656. * Creates a Viewport object located at (x, y) and sized (width, height).
  6657. */
  6658. function Viewport(x, y, width, height) {
  6659. this.x = x;
  6660. this.y = y;
  6661. this.width = width;
  6662. this.height = height;
  6663. }
  6664. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6665. if (renderWidthOrEngine.getRenderWidth) {
  6666. var engine = renderWidthOrEngine;
  6667. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6668. }
  6669. var renderWidth = renderWidthOrEngine;
  6670. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6671. };
  6672. /**
  6673. * Returns a new Viewport copied from the current one.
  6674. */
  6675. Viewport.prototype.clone = function () {
  6676. return new Viewport(this.x, this.y, this.width, this.height);
  6677. };
  6678. return Viewport;
  6679. }());
  6680. BABYLON.Viewport = Viewport;
  6681. var Frustum = /** @class */ (function () {
  6682. function Frustum() {
  6683. }
  6684. /**
  6685. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6686. */
  6687. Frustum.GetPlanes = function (transform) {
  6688. var frustumPlanes = [];
  6689. for (var index = 0; index < 6; index++) {
  6690. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6691. }
  6692. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6693. return frustumPlanes;
  6694. };
  6695. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6696. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6697. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6698. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6699. frustumPlane.d = transform.m[15] + transform.m[14];
  6700. frustumPlane.normalize();
  6701. };
  6702. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6703. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6704. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6705. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6706. frustumPlane.d = transform.m[15] - transform.m[14];
  6707. frustumPlane.normalize();
  6708. };
  6709. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6710. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6711. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6712. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6713. frustumPlane.d = transform.m[15] + transform.m[12];
  6714. frustumPlane.normalize();
  6715. };
  6716. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6717. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6718. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6719. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6720. frustumPlane.d = transform.m[15] - transform.m[12];
  6721. frustumPlane.normalize();
  6722. };
  6723. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6724. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6725. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6726. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6727. frustumPlane.d = transform.m[15] - transform.m[13];
  6728. frustumPlane.normalize();
  6729. };
  6730. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6731. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6732. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6733. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6734. frustumPlane.d = transform.m[15] + transform.m[13];
  6735. frustumPlane.normalize();
  6736. };
  6737. /**
  6738. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6739. */
  6740. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6741. // Near
  6742. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6743. // Far
  6744. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6745. // Left
  6746. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6747. // Right
  6748. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6749. // Top
  6750. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6751. // Bottom
  6752. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6753. };
  6754. return Frustum;
  6755. }());
  6756. BABYLON.Frustum = Frustum;
  6757. /** Defines supported spaces */
  6758. var Space;
  6759. (function (Space) {
  6760. /** Local (object) space */
  6761. Space[Space["LOCAL"] = 0] = "LOCAL";
  6762. /** World space */
  6763. Space[Space["WORLD"] = 1] = "WORLD";
  6764. /** Bone space */
  6765. Space[Space["BONE"] = 2] = "BONE";
  6766. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6767. /** Defines the 3 main axes */
  6768. var Axis = /** @class */ (function () {
  6769. function Axis() {
  6770. }
  6771. /** X axis */
  6772. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6773. /** Y axis */
  6774. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6775. /** Z axis */
  6776. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6777. return Axis;
  6778. }());
  6779. BABYLON.Axis = Axis;
  6780. ;
  6781. var BezierCurve = /** @class */ (function () {
  6782. function BezierCurve() {
  6783. }
  6784. /**
  6785. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6786. */
  6787. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6788. // Extract X (which is equal to time here)
  6789. var f0 = 1 - 3 * x2 + 3 * x1;
  6790. var f1 = 3 * x2 - 6 * x1;
  6791. var f2 = 3 * x1;
  6792. var refinedT = t;
  6793. for (var i = 0; i < 5; i++) {
  6794. var refinedT2 = refinedT * refinedT;
  6795. var refinedT3 = refinedT2 * refinedT;
  6796. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6797. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6798. refinedT -= (x - t) * slope;
  6799. refinedT = Math.min(1, Math.max(0, refinedT));
  6800. }
  6801. // Resolve cubic bezier for the given x
  6802. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6803. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6804. Math.pow(refinedT, 3);
  6805. };
  6806. return BezierCurve;
  6807. }());
  6808. BABYLON.BezierCurve = BezierCurve;
  6809. /**
  6810. * Defines potential orientation for back face culling
  6811. */
  6812. var Orientation;
  6813. (function (Orientation) {
  6814. /**
  6815. * Clockwise
  6816. */
  6817. Orientation[Orientation["CW"] = 0] = "CW";
  6818. /** Counter clockwise */
  6819. Orientation[Orientation["CCW"] = 1] = "CCW";
  6820. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6821. /**
  6822. * Defines angle representation
  6823. */
  6824. var Angle = /** @class */ (function () {
  6825. /**
  6826. * Creates an Angle object of "radians" radians (float).
  6827. */
  6828. function Angle(radians) {
  6829. this._radians = radians;
  6830. if (this._radians < 0.0)
  6831. this._radians += (2.0 * Math.PI);
  6832. }
  6833. /**
  6834. * Get value in degrees
  6835. * @returns the Angle value in degrees (float)
  6836. */
  6837. Angle.prototype.degrees = function () {
  6838. return this._radians * 180.0 / Math.PI;
  6839. };
  6840. /**
  6841. * Get value in radians
  6842. * @returns the Angle value in radians (float)
  6843. */
  6844. Angle.prototype.radians = function () {
  6845. return this._radians;
  6846. };
  6847. /**
  6848. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6849. * @param a defines first vector
  6850. * @param b defines second vector
  6851. * @returns a new Angle
  6852. */
  6853. Angle.BetweenTwoPoints = function (a, b) {
  6854. var delta = b.subtract(a);
  6855. var theta = Math.atan2(delta.y, delta.x);
  6856. return new Angle(theta);
  6857. };
  6858. /**
  6859. * Gets a new Angle object from the given float in radians
  6860. * @param radians defines the angle value in radians
  6861. * @returns a new Angle
  6862. */
  6863. Angle.FromRadians = function (radians) {
  6864. return new Angle(radians);
  6865. };
  6866. /**
  6867. * Gets a new Angle object from the given float in degrees
  6868. * @param degrees defines the angle value in degrees
  6869. * @returns a new Angle
  6870. */
  6871. Angle.FromDegrees = function (degrees) {
  6872. return new Angle(degrees * Math.PI / 180.0);
  6873. };
  6874. return Angle;
  6875. }());
  6876. BABYLON.Angle = Angle;
  6877. var Arc2 = /** @class */ (function () {
  6878. /**
  6879. * Creates an Arc object from the three given points : start, middle and end.
  6880. */
  6881. function Arc2(startPoint, midPoint, endPoint) {
  6882. this.startPoint = startPoint;
  6883. this.midPoint = midPoint;
  6884. this.endPoint = endPoint;
  6885. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6886. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6887. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6888. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6889. 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);
  6890. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6891. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6892. var a1 = this.startAngle.degrees();
  6893. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6894. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6895. // angles correction
  6896. if (a2 - a1 > +180.0)
  6897. a2 -= 360.0;
  6898. if (a2 - a1 < -180.0)
  6899. a2 += 360.0;
  6900. if (a3 - a2 > +180.0)
  6901. a3 -= 360.0;
  6902. if (a3 - a2 < -180.0)
  6903. a3 += 360.0;
  6904. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6905. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6906. }
  6907. return Arc2;
  6908. }());
  6909. BABYLON.Arc2 = Arc2;
  6910. var Path2 = /** @class */ (function () {
  6911. /**
  6912. * Creates a Path2 object from the starting 2D coordinates x and y.
  6913. */
  6914. function Path2(x, y) {
  6915. this._points = new Array();
  6916. this._length = 0.0;
  6917. this.closed = false;
  6918. this._points.push(new Vector2(x, y));
  6919. }
  6920. /**
  6921. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6922. * Returns the updated Path2.
  6923. */
  6924. Path2.prototype.addLineTo = function (x, y) {
  6925. if (this.closed) {
  6926. return this;
  6927. }
  6928. var newPoint = new Vector2(x, y);
  6929. var previousPoint = this._points[this._points.length - 1];
  6930. this._points.push(newPoint);
  6931. this._length += newPoint.subtract(previousPoint).length();
  6932. return this;
  6933. };
  6934. /**
  6935. * 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.
  6936. * Returns the updated Path2.
  6937. */
  6938. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6939. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6940. if (this.closed) {
  6941. return this;
  6942. }
  6943. var startPoint = this._points[this._points.length - 1];
  6944. var midPoint = new Vector2(midX, midY);
  6945. var endPoint = new Vector2(endX, endY);
  6946. var arc = new Arc2(startPoint, midPoint, endPoint);
  6947. var increment = arc.angle.radians() / numberOfSegments;
  6948. if (arc.orientation === Orientation.CW)
  6949. increment *= -1;
  6950. var currentAngle = arc.startAngle.radians() + increment;
  6951. for (var i = 0; i < numberOfSegments; i++) {
  6952. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6953. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6954. this.addLineTo(x, y);
  6955. currentAngle += increment;
  6956. }
  6957. return this;
  6958. };
  6959. /**
  6960. * Closes the Path2.
  6961. * Returns the Path2.
  6962. */
  6963. Path2.prototype.close = function () {
  6964. this.closed = true;
  6965. return this;
  6966. };
  6967. /**
  6968. * Returns the Path2 total length (float).
  6969. */
  6970. Path2.prototype.length = function () {
  6971. var result = this._length;
  6972. if (!this.closed) {
  6973. var lastPoint = this._points[this._points.length - 1];
  6974. var firstPoint = this._points[0];
  6975. result += (firstPoint.subtract(lastPoint).length());
  6976. }
  6977. return result;
  6978. };
  6979. /**
  6980. * Returns the Path2 internal array of points.
  6981. */
  6982. Path2.prototype.getPoints = function () {
  6983. return this._points;
  6984. };
  6985. /**
  6986. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6987. */
  6988. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6989. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6990. return Vector2.Zero();
  6991. }
  6992. var lengthPosition = normalizedLengthPosition * this.length();
  6993. var previousOffset = 0;
  6994. for (var i = 0; i < this._points.length; i++) {
  6995. var j = (i + 1) % this._points.length;
  6996. var a = this._points[i];
  6997. var b = this._points[j];
  6998. var bToA = b.subtract(a);
  6999. var nextOffset = (bToA.length() + previousOffset);
  7000. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7001. var dir = bToA.normalize();
  7002. var localOffset = lengthPosition - previousOffset;
  7003. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7004. }
  7005. previousOffset = nextOffset;
  7006. }
  7007. return Vector2.Zero();
  7008. };
  7009. /**
  7010. * Returns a new Path2 starting at the coordinates (x, y).
  7011. */
  7012. Path2.StartingAt = function (x, y) {
  7013. return new Path2(x, y);
  7014. };
  7015. return Path2;
  7016. }());
  7017. BABYLON.Path2 = Path2;
  7018. var Path3D = /** @class */ (function () {
  7019. /**
  7020. * new Path3D(path, normal, raw)
  7021. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7022. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7023. * path : an array of Vector3, the curve axis of the Path3D
  7024. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7025. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7026. */
  7027. function Path3D(path, firstNormal, raw) {
  7028. if (firstNormal === void 0) { firstNormal = null; }
  7029. this.path = path;
  7030. this._curve = new Array();
  7031. this._distances = new Array();
  7032. this._tangents = new Array();
  7033. this._normals = new Array();
  7034. this._binormals = new Array();
  7035. for (var p = 0; p < path.length; p++) {
  7036. this._curve[p] = path[p].clone(); // hard copy
  7037. }
  7038. this._raw = raw || false;
  7039. this._compute(firstNormal);
  7040. }
  7041. /**
  7042. * Returns the Path3D array of successive Vector3 designing its curve.
  7043. */
  7044. Path3D.prototype.getCurve = function () {
  7045. return this._curve;
  7046. };
  7047. /**
  7048. * Returns an array populated with tangent vectors on each Path3D curve point.
  7049. */
  7050. Path3D.prototype.getTangents = function () {
  7051. return this._tangents;
  7052. };
  7053. /**
  7054. * Returns an array populated with normal vectors on each Path3D curve point.
  7055. */
  7056. Path3D.prototype.getNormals = function () {
  7057. return this._normals;
  7058. };
  7059. /**
  7060. * Returns an array populated with binormal vectors on each Path3D curve point.
  7061. */
  7062. Path3D.prototype.getBinormals = function () {
  7063. return this._binormals;
  7064. };
  7065. /**
  7066. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7067. */
  7068. Path3D.prototype.getDistances = function () {
  7069. return this._distances;
  7070. };
  7071. /**
  7072. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7073. * Returns the same object updated.
  7074. */
  7075. Path3D.prototype.update = function (path, firstNormal) {
  7076. if (firstNormal === void 0) { firstNormal = null; }
  7077. for (var p = 0; p < path.length; p++) {
  7078. this._curve[p].x = path[p].x;
  7079. this._curve[p].y = path[p].y;
  7080. this._curve[p].z = path[p].z;
  7081. }
  7082. this._compute(firstNormal);
  7083. return this;
  7084. };
  7085. // private function compute() : computes tangents, normals and binormals
  7086. Path3D.prototype._compute = function (firstNormal) {
  7087. var l = this._curve.length;
  7088. // first and last tangents
  7089. this._tangents[0] = this._getFirstNonNullVector(0);
  7090. if (!this._raw) {
  7091. this._tangents[0].normalize();
  7092. }
  7093. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7094. if (!this._raw) {
  7095. this._tangents[l - 1].normalize();
  7096. }
  7097. // normals and binormals at first point : arbitrary vector with _normalVector()
  7098. var tg0 = this._tangents[0];
  7099. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7100. this._normals[0] = pp0;
  7101. if (!this._raw) {
  7102. this._normals[0].normalize();
  7103. }
  7104. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7105. if (!this._raw) {
  7106. this._binormals[0].normalize();
  7107. }
  7108. this._distances[0] = 0.0;
  7109. // normals and binormals : next points
  7110. var prev; // previous vector (segment)
  7111. var cur; // current vector (segment)
  7112. var curTang; // current tangent
  7113. // previous normal
  7114. var prevBinor; // previous binormal
  7115. for (var i = 1; i < l; i++) {
  7116. // tangents
  7117. prev = this._getLastNonNullVector(i);
  7118. if (i < l - 1) {
  7119. cur = this._getFirstNonNullVector(i);
  7120. this._tangents[i] = prev.add(cur);
  7121. this._tangents[i].normalize();
  7122. }
  7123. this._distances[i] = this._distances[i - 1] + prev.length();
  7124. // normals and binormals
  7125. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7126. curTang = this._tangents[i];
  7127. prevBinor = this._binormals[i - 1];
  7128. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7129. if (!this._raw) {
  7130. this._normals[i].normalize();
  7131. }
  7132. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7133. if (!this._raw) {
  7134. this._binormals[i].normalize();
  7135. }
  7136. }
  7137. };
  7138. // private function getFirstNonNullVector(index)
  7139. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7140. Path3D.prototype._getFirstNonNullVector = function (index) {
  7141. var i = 1;
  7142. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7143. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7144. i++;
  7145. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7146. }
  7147. return nNVector;
  7148. };
  7149. // private function getLastNonNullVector(index)
  7150. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7151. Path3D.prototype._getLastNonNullVector = function (index) {
  7152. var i = 1;
  7153. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7154. while (nLVector.length() === 0 && index > i + 1) {
  7155. i++;
  7156. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7157. }
  7158. return nLVector;
  7159. };
  7160. // private function normalVector(v0, vt, va) :
  7161. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7162. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7163. Path3D.prototype._normalVector = function (v0, vt, va) {
  7164. var normal0;
  7165. var tgl = vt.length();
  7166. if (tgl === 0.0) {
  7167. tgl = 1.0;
  7168. }
  7169. if (va === undefined || va === null) {
  7170. var point;
  7171. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7172. point = new Vector3(0.0, -1.0, 0.0);
  7173. }
  7174. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7175. point = new Vector3(1.0, 0.0, 0.0);
  7176. }
  7177. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7178. point = new Vector3(0.0, 0.0, 1.0);
  7179. }
  7180. else {
  7181. point = Vector3.Zero();
  7182. }
  7183. normal0 = Vector3.Cross(vt, point);
  7184. }
  7185. else {
  7186. normal0 = Vector3.Cross(vt, va);
  7187. Vector3.CrossToRef(normal0, vt, normal0);
  7188. }
  7189. normal0.normalize();
  7190. return normal0;
  7191. };
  7192. return Path3D;
  7193. }());
  7194. BABYLON.Path3D = Path3D;
  7195. var Curve3 = /** @class */ (function () {
  7196. /**
  7197. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7198. * A Curve3 is designed from a series of successive Vector3.
  7199. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7200. */
  7201. function Curve3(points) {
  7202. this._length = 0.0;
  7203. this._points = points;
  7204. this._length = this._computeLength(points);
  7205. }
  7206. /**
  7207. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7208. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7209. * @param v1 (Vector3) the control point
  7210. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7211. * @param nbPoints (integer) the wanted number of points in the curve
  7212. */
  7213. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7214. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7215. var bez = new Array();
  7216. var equation = function (t, val0, val1, val2) {
  7217. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7218. return res;
  7219. };
  7220. for (var i = 0; i <= nbPoints; i++) {
  7221. 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)));
  7222. }
  7223. return new Curve3(bez);
  7224. };
  7225. /**
  7226. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7227. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7228. * @param v1 (Vector3) the first control point
  7229. * @param v2 (Vector3) the second control point
  7230. * @param v3 (Vector3) the end point of the Cubic Bezier
  7231. * @param nbPoints (integer) the wanted number of points in the curve
  7232. */
  7233. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7234. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7235. var bez = new Array();
  7236. var equation = function (t, val0, val1, val2, val3) {
  7237. 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;
  7238. return res;
  7239. };
  7240. for (var i = 0; i <= nbPoints; i++) {
  7241. 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)));
  7242. }
  7243. return new Curve3(bez);
  7244. };
  7245. /**
  7246. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7247. * @param p1 (Vector3) the origin point of the Hermite Spline
  7248. * @param t1 (Vector3) the tangent vector at the origin point
  7249. * @param p2 (Vector3) the end point of the Hermite Spline
  7250. * @param t2 (Vector3) the tangent vector at the end point
  7251. * @param nbPoints (integer) the wanted number of points in the curve
  7252. */
  7253. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7254. var hermite = new Array();
  7255. var step = 1.0 / nbPoints;
  7256. for (var i = 0; i <= nbPoints; i++) {
  7257. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7258. }
  7259. return new Curve3(hermite);
  7260. };
  7261. /**
  7262. * Returns a Curve3 object along a CatmullRom Spline curve :
  7263. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7264. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7265. */
  7266. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7267. var totalPoints = new Array();
  7268. totalPoints.push(points[0].clone());
  7269. Array.prototype.push.apply(totalPoints, points);
  7270. totalPoints.push(points[points.length - 1].clone());
  7271. var catmullRom = new Array();
  7272. var step = 1.0 / nbPoints;
  7273. var amount = 0.0;
  7274. for (var i = 0; i < totalPoints.length - 3; i++) {
  7275. amount = 0;
  7276. for (var c = 0; c < nbPoints; c++) {
  7277. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7278. amount += step;
  7279. }
  7280. }
  7281. i--;
  7282. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7283. return new Curve3(catmullRom);
  7284. };
  7285. /**
  7286. * Returns the Curve3 stored array of successive Vector3
  7287. */
  7288. Curve3.prototype.getPoints = function () {
  7289. return this._points;
  7290. };
  7291. /**
  7292. * Returns the computed length (float) of the curve.
  7293. */
  7294. Curve3.prototype.length = function () {
  7295. return this._length;
  7296. };
  7297. /**
  7298. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7299. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7300. * curveA and curveB keep unchanged.
  7301. */
  7302. Curve3.prototype.continue = function (curve) {
  7303. var lastPoint = this._points[this._points.length - 1];
  7304. var continuedPoints = this._points.slice();
  7305. var curvePoints = curve.getPoints();
  7306. for (var i = 1; i < curvePoints.length; i++) {
  7307. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7308. }
  7309. var continuedCurve = new Curve3(continuedPoints);
  7310. return continuedCurve;
  7311. };
  7312. Curve3.prototype._computeLength = function (path) {
  7313. var l = 0;
  7314. for (var i = 1; i < path.length; i++) {
  7315. l += (path[i].subtract(path[i - 1])).length();
  7316. }
  7317. return l;
  7318. };
  7319. return Curve3;
  7320. }());
  7321. BABYLON.Curve3 = Curve3;
  7322. // Vertex formats
  7323. var PositionNormalVertex = /** @class */ (function () {
  7324. function PositionNormalVertex(position, normal) {
  7325. if (position === void 0) { position = Vector3.Zero(); }
  7326. if (normal === void 0) { normal = Vector3.Up(); }
  7327. this.position = position;
  7328. this.normal = normal;
  7329. }
  7330. PositionNormalVertex.prototype.clone = function () {
  7331. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7332. };
  7333. return PositionNormalVertex;
  7334. }());
  7335. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7336. var PositionNormalTextureVertex = /** @class */ (function () {
  7337. function PositionNormalTextureVertex(position, normal, uv) {
  7338. if (position === void 0) { position = Vector3.Zero(); }
  7339. if (normal === void 0) { normal = Vector3.Up(); }
  7340. if (uv === void 0) { uv = Vector2.Zero(); }
  7341. this.position = position;
  7342. this.normal = normal;
  7343. this.uv = uv;
  7344. }
  7345. PositionNormalTextureVertex.prototype.clone = function () {
  7346. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7347. };
  7348. return PositionNormalTextureVertex;
  7349. }());
  7350. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7351. // Temporary pre-allocated objects for engine internal use
  7352. // usage in any internal function :
  7353. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7354. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7355. var Tmp = /** @class */ (function () {
  7356. function Tmp() {
  7357. }
  7358. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7359. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7360. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7361. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7362. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7363. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7364. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7365. Matrix.Zero(), Matrix.Zero(),
  7366. Matrix.Zero(), Matrix.Zero(),
  7367. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7368. return Tmp;
  7369. }());
  7370. BABYLON.Tmp = Tmp;
  7371. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7372. var MathTmp = /** @class */ (function () {
  7373. function MathTmp() {
  7374. }
  7375. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7376. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7377. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7378. return MathTmp;
  7379. }());
  7380. })(BABYLON || (BABYLON = {}));
  7381. //# sourceMappingURL=babylon.math.js.map
  7382. var BABYLON;
  7383. (function (BABYLON) {
  7384. var Scalar = /** @class */ (function () {
  7385. function Scalar() {
  7386. }
  7387. /**
  7388. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7389. */
  7390. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7391. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7392. var num = a - b;
  7393. return -epsilon <= num && num <= epsilon;
  7394. };
  7395. /**
  7396. * Returns a string : the upper case translation of the number i to hexadecimal.
  7397. */
  7398. Scalar.ToHex = function (i) {
  7399. var str = i.toString(16);
  7400. if (i <= 15) {
  7401. return ("0" + str).toUpperCase();
  7402. }
  7403. return str.toUpperCase();
  7404. };
  7405. /**
  7406. * Returns -1 if value is negative and +1 is value is positive.
  7407. * Returns the value itself if it's equal to zero.
  7408. */
  7409. Scalar.Sign = function (value) {
  7410. value = +value; // convert to a number
  7411. if (value === 0 || isNaN(value))
  7412. return value;
  7413. return value > 0 ? 1 : -1;
  7414. };
  7415. /**
  7416. * Returns the value itself if it's between min and max.
  7417. * Returns min if the value is lower than min.
  7418. * Returns max if the value is greater than max.
  7419. */
  7420. Scalar.Clamp = function (value, min, max) {
  7421. if (min === void 0) { min = 0; }
  7422. if (max === void 0) { max = 1; }
  7423. return Math.min(max, Math.max(min, value));
  7424. };
  7425. /**
  7426. * Returns the log2 of value.
  7427. */
  7428. Scalar.Log2 = function (value) {
  7429. return Math.log(value) * Math.LOG2E;
  7430. };
  7431. /**
  7432. * Loops the value, so that it is never larger than length and never smaller than 0.
  7433. *
  7434. * This is similar to the modulo operator but it works with floating point numbers.
  7435. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7436. * With t = 5 and length = 2.5, the result would be 0.0.
  7437. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7438. */
  7439. Scalar.Repeat = function (value, length) {
  7440. return value - Math.floor(value / length) * length;
  7441. };
  7442. /**
  7443. * Normalize the value between 0.0 and 1.0 using min and max values
  7444. */
  7445. Scalar.Normalize = function (value, min, max) {
  7446. return (value - min) / (max - min);
  7447. };
  7448. /**
  7449. * Denormalize the value from 0.0 and 1.0 using min and max values
  7450. */
  7451. Scalar.Denormalize = function (normalized, min, max) {
  7452. return (normalized * (max - min) + min);
  7453. };
  7454. /**
  7455. * Calculates the shortest difference between two given angles given in degrees.
  7456. */
  7457. Scalar.DeltaAngle = function (current, target) {
  7458. var num = Scalar.Repeat(target - current, 360.0);
  7459. if (num > 180.0) {
  7460. num -= 360.0;
  7461. }
  7462. return num;
  7463. };
  7464. /**
  7465. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7466. *
  7467. * The returned value will move back and forth between 0 and length
  7468. */
  7469. Scalar.PingPong = function (tx, length) {
  7470. var t = Scalar.Repeat(tx, length * 2.0);
  7471. return length - Math.abs(t - length);
  7472. };
  7473. /**
  7474. * Interpolates between min and max with smoothing at the limits.
  7475. *
  7476. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7477. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7478. */
  7479. Scalar.SmoothStep = function (from, to, tx) {
  7480. var t = Scalar.Clamp(tx);
  7481. t = -2.0 * t * t * t + 3.0 * t * t;
  7482. return to * t + from * (1.0 - t);
  7483. };
  7484. /**
  7485. * Moves a value current towards target.
  7486. *
  7487. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7488. * Negative values of maxDelta pushes the value away from target.
  7489. */
  7490. Scalar.MoveTowards = function (current, target, maxDelta) {
  7491. var result = 0;
  7492. if (Math.abs(target - current) <= maxDelta) {
  7493. result = target;
  7494. }
  7495. else {
  7496. result = current + Scalar.Sign(target - current) * maxDelta;
  7497. }
  7498. return result;
  7499. };
  7500. /**
  7501. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7502. *
  7503. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7504. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7505. */
  7506. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7507. var num = Scalar.DeltaAngle(current, target);
  7508. var result = 0;
  7509. if (-maxDelta < num && num < maxDelta) {
  7510. result = target;
  7511. }
  7512. else {
  7513. target = current + num;
  7514. result = Scalar.MoveTowards(current, target, maxDelta);
  7515. }
  7516. return result;
  7517. };
  7518. /**
  7519. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7520. */
  7521. Scalar.Lerp = function (start, end, amount) {
  7522. return start + ((end - start) * amount);
  7523. };
  7524. /**
  7525. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7526. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7527. */
  7528. Scalar.LerpAngle = function (start, end, amount) {
  7529. var num = Scalar.Repeat(end - start, 360.0);
  7530. if (num > 180.0) {
  7531. num -= 360.0;
  7532. }
  7533. return start + num * Scalar.Clamp(amount);
  7534. };
  7535. /**
  7536. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7537. */
  7538. Scalar.InverseLerp = function (a, b, value) {
  7539. var result = 0;
  7540. if (a != b) {
  7541. result = Scalar.Clamp((value - a) / (b - a));
  7542. }
  7543. else {
  7544. result = 0.0;
  7545. }
  7546. return result;
  7547. };
  7548. /**
  7549. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7550. */
  7551. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7552. var squared = amount * amount;
  7553. var cubed = amount * squared;
  7554. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7555. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7556. var part3 = (cubed - (2.0 * squared)) + amount;
  7557. var part4 = cubed - squared;
  7558. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7559. };
  7560. /**
  7561. * Returns a random float number between and min and max values
  7562. */
  7563. Scalar.RandomRange = function (min, max) {
  7564. if (min === max)
  7565. return min;
  7566. return ((Math.random() * (max - min)) + min);
  7567. };
  7568. /**
  7569. * This function returns percentage of a number in a given range.
  7570. *
  7571. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7572. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7573. */
  7574. Scalar.RangeToPercent = function (number, min, max) {
  7575. return ((number - min) / (max - min));
  7576. };
  7577. /**
  7578. * This function returns number that corresponds to the percentage in a given range.
  7579. *
  7580. * PercentToRange(0.34,0,100) will return 34.
  7581. */
  7582. Scalar.PercentToRange = function (percent, min, max) {
  7583. return ((max - min) * percent + min);
  7584. };
  7585. /**
  7586. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7587. * @param angle The angle to normalize in radian.
  7588. * @return The converted angle.
  7589. */
  7590. Scalar.NormalizeRadians = function (angle) {
  7591. // More precise but slower version kept for reference.
  7592. // angle = angle % Tools.TwoPi;
  7593. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7594. //if (angle > Math.PI) {
  7595. // angle -= Tools.TwoPi;
  7596. //}
  7597. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7598. return angle;
  7599. };
  7600. /**
  7601. * Two pi constants convenient for computation.
  7602. */
  7603. Scalar.TwoPi = Math.PI * 2;
  7604. return Scalar;
  7605. }());
  7606. BABYLON.Scalar = Scalar;
  7607. })(BABYLON || (BABYLON = {}));
  7608. //# sourceMappingURL=babylon.math.scalar.js.map
  7609. //# sourceMappingURL=babylon.mixins.js.map
  7610. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7611. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7612. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7613. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7614. //# sourceMappingURL=babylon.webgl2.js.map
  7615. var BABYLON;
  7616. (function (BABYLON) {
  7617. var __decoratorInitialStore = {};
  7618. var __mergedStore = {};
  7619. var _copySource = function (creationFunction, source, instanciate) {
  7620. var destination = creationFunction();
  7621. // Tags
  7622. if (BABYLON.Tags) {
  7623. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7624. }
  7625. var classStore = getMergedStore(destination);
  7626. // Properties
  7627. for (var property in classStore) {
  7628. var propertyDescriptor = classStore[property];
  7629. var sourceProperty = source[property];
  7630. var propertyType = propertyDescriptor.type;
  7631. if (sourceProperty !== undefined && sourceProperty !== null) {
  7632. switch (propertyType) {
  7633. case 0: // Value
  7634. case 6: // Mesh reference
  7635. case 11: // Camera reference
  7636. destination[property] = sourceProperty;
  7637. break;
  7638. case 1: // Texture
  7639. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7640. break;
  7641. case 2: // Color3
  7642. case 3: // FresnelParameters
  7643. case 4: // Vector2
  7644. case 5: // Vector3
  7645. case 7: // Color Curves
  7646. case 10: // Quaternion
  7647. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7648. break;
  7649. }
  7650. }
  7651. }
  7652. return destination;
  7653. };
  7654. function getDirectStore(target) {
  7655. var classKey = target.getClassName();
  7656. if (!__decoratorInitialStore[classKey]) {
  7657. __decoratorInitialStore[classKey] = {};
  7658. }
  7659. return __decoratorInitialStore[classKey];
  7660. }
  7661. /**
  7662. * Return the list of properties flagged as serializable
  7663. * @param target: host object
  7664. */
  7665. function getMergedStore(target) {
  7666. var classKey = target.getClassName();
  7667. if (__mergedStore[classKey]) {
  7668. return __mergedStore[classKey];
  7669. }
  7670. __mergedStore[classKey] = {};
  7671. var store = __mergedStore[classKey];
  7672. var currentTarget = target;
  7673. var currentKey = classKey;
  7674. while (currentKey) {
  7675. var initialStore = __decoratorInitialStore[currentKey];
  7676. for (var property in initialStore) {
  7677. store[property] = initialStore[property];
  7678. }
  7679. var parent_1 = void 0;
  7680. var done = false;
  7681. do {
  7682. parent_1 = Object.getPrototypeOf(currentTarget);
  7683. if (!parent_1.getClassName) {
  7684. done = true;
  7685. break;
  7686. }
  7687. if (parent_1.getClassName() !== currentKey) {
  7688. break;
  7689. }
  7690. currentTarget = parent_1;
  7691. } while (parent_1);
  7692. if (done) {
  7693. break;
  7694. }
  7695. currentKey = parent_1.getClassName();
  7696. currentTarget = parent_1;
  7697. }
  7698. return store;
  7699. }
  7700. function generateSerializableMember(type, sourceName) {
  7701. return function (target, propertyKey) {
  7702. var classStore = getDirectStore(target);
  7703. if (!classStore[propertyKey]) {
  7704. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7705. }
  7706. };
  7707. }
  7708. function generateExpandMember(setCallback, targetKey) {
  7709. if (targetKey === void 0) { targetKey = null; }
  7710. return function (target, propertyKey) {
  7711. var key = targetKey || ("_" + propertyKey);
  7712. Object.defineProperty(target, propertyKey, {
  7713. get: function () {
  7714. return this[key];
  7715. },
  7716. set: function (value) {
  7717. if (this[key] === value) {
  7718. return;
  7719. }
  7720. this[key] = value;
  7721. target[setCallback].apply(this);
  7722. },
  7723. enumerable: true,
  7724. configurable: true
  7725. });
  7726. };
  7727. }
  7728. function expandToProperty(callback, targetKey) {
  7729. if (targetKey === void 0) { targetKey = null; }
  7730. return generateExpandMember(callback, targetKey);
  7731. }
  7732. BABYLON.expandToProperty = expandToProperty;
  7733. function serialize(sourceName) {
  7734. return generateSerializableMember(0, sourceName); // value member
  7735. }
  7736. BABYLON.serialize = serialize;
  7737. function serializeAsTexture(sourceName) {
  7738. return generateSerializableMember(1, sourceName); // texture member
  7739. }
  7740. BABYLON.serializeAsTexture = serializeAsTexture;
  7741. function serializeAsColor3(sourceName) {
  7742. return generateSerializableMember(2, sourceName); // color3 member
  7743. }
  7744. BABYLON.serializeAsColor3 = serializeAsColor3;
  7745. function serializeAsFresnelParameters(sourceName) {
  7746. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7747. }
  7748. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7749. function serializeAsVector2(sourceName) {
  7750. return generateSerializableMember(4, sourceName); // vector2 member
  7751. }
  7752. BABYLON.serializeAsVector2 = serializeAsVector2;
  7753. function serializeAsVector3(sourceName) {
  7754. return generateSerializableMember(5, sourceName); // vector3 member
  7755. }
  7756. BABYLON.serializeAsVector3 = serializeAsVector3;
  7757. function serializeAsMeshReference(sourceName) {
  7758. return generateSerializableMember(6, sourceName); // mesh reference member
  7759. }
  7760. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7761. function serializeAsColorCurves(sourceName) {
  7762. return generateSerializableMember(7, sourceName); // color curves
  7763. }
  7764. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7765. function serializeAsColor4(sourceName) {
  7766. return generateSerializableMember(8, sourceName); // color 4
  7767. }
  7768. BABYLON.serializeAsColor4 = serializeAsColor4;
  7769. function serializeAsImageProcessingConfiguration(sourceName) {
  7770. return generateSerializableMember(9, sourceName); // image processing
  7771. }
  7772. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7773. function serializeAsQuaternion(sourceName) {
  7774. return generateSerializableMember(10, sourceName); // quaternion member
  7775. }
  7776. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7777. /**
  7778. * Decorator used to define property that can be serialized as reference to a camera
  7779. * @param sourceName defines the name of the property to decorate
  7780. */
  7781. function serializeAsCameraReference(sourceName) {
  7782. return generateSerializableMember(11, sourceName); // camera reference member
  7783. }
  7784. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7785. var SerializationHelper = /** @class */ (function () {
  7786. function SerializationHelper() {
  7787. }
  7788. SerializationHelper.Serialize = function (entity, serializationObject) {
  7789. if (!serializationObject) {
  7790. serializationObject = {};
  7791. }
  7792. // Tags
  7793. if (BABYLON.Tags) {
  7794. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7795. }
  7796. var serializedProperties = getMergedStore(entity);
  7797. // Properties
  7798. for (var property in serializedProperties) {
  7799. var propertyDescriptor = serializedProperties[property];
  7800. var targetPropertyName = propertyDescriptor.sourceName || property;
  7801. var propertyType = propertyDescriptor.type;
  7802. var sourceProperty = entity[property];
  7803. if (sourceProperty !== undefined && sourceProperty !== null) {
  7804. switch (propertyType) {
  7805. case 0: // Value
  7806. serializationObject[targetPropertyName] = sourceProperty;
  7807. break;
  7808. case 1: // Texture
  7809. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7810. break;
  7811. case 2: // Color3
  7812. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7813. break;
  7814. case 3: // FresnelParameters
  7815. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7816. break;
  7817. case 4: // Vector2
  7818. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7819. break;
  7820. case 5: // Vector3
  7821. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7822. break;
  7823. case 6: // Mesh reference
  7824. serializationObject[targetPropertyName] = sourceProperty.id;
  7825. break;
  7826. case 7: // Color Curves
  7827. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7828. break;
  7829. case 8: // Color 4
  7830. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7831. break;
  7832. case 9: // Image Processing
  7833. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7834. break;
  7835. case 10: // Quaternion
  7836. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7837. break;
  7838. case 11: // Camera reference
  7839. serializationObject[targetPropertyName] = sourceProperty.id;
  7840. break;
  7841. }
  7842. }
  7843. }
  7844. return serializationObject;
  7845. };
  7846. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7847. if (rootUrl === void 0) { rootUrl = null; }
  7848. var destination = creationFunction();
  7849. if (!rootUrl) {
  7850. rootUrl = "";
  7851. }
  7852. // Tags
  7853. if (BABYLON.Tags) {
  7854. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7855. }
  7856. var classStore = getMergedStore(destination);
  7857. // Properties
  7858. for (var property in classStore) {
  7859. var propertyDescriptor = classStore[property];
  7860. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7861. var propertyType = propertyDescriptor.type;
  7862. if (sourceProperty !== undefined && sourceProperty !== null) {
  7863. var dest = destination;
  7864. switch (propertyType) {
  7865. case 0: // Value
  7866. dest[property] = sourceProperty;
  7867. break;
  7868. case 1: // Texture
  7869. if (scene) {
  7870. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7871. }
  7872. break;
  7873. case 2: // Color3
  7874. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7875. break;
  7876. case 3: // FresnelParameters
  7877. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7878. break;
  7879. case 4: // Vector2
  7880. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7881. break;
  7882. case 5: // Vector3
  7883. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7884. break;
  7885. case 6: // Mesh reference
  7886. if (scene) {
  7887. dest[property] = scene.getLastMeshByID(sourceProperty);
  7888. }
  7889. break;
  7890. case 7: // Color Curves
  7891. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7892. break;
  7893. case 8: // Color 4
  7894. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7895. break;
  7896. case 9: // Image Processing
  7897. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7898. break;
  7899. case 10: // Quaternion
  7900. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7901. break;
  7902. case 11: // Camera reference
  7903. if (scene) {
  7904. dest[property] = scene.getCameraByID(sourceProperty);
  7905. }
  7906. break;
  7907. }
  7908. }
  7909. }
  7910. return destination;
  7911. };
  7912. SerializationHelper.Clone = function (creationFunction, source) {
  7913. return _copySource(creationFunction, source, false);
  7914. };
  7915. SerializationHelper.Instanciate = function (creationFunction, source) {
  7916. return _copySource(creationFunction, source, true);
  7917. };
  7918. return SerializationHelper;
  7919. }());
  7920. BABYLON.SerializationHelper = SerializationHelper;
  7921. })(BABYLON || (BABYLON = {}));
  7922. //# sourceMappingURL=babylon.decorators.js.map
  7923. var BABYLON;
  7924. (function (BABYLON) {
  7925. /**
  7926. * Wrapper class for promise with external resolve and reject.
  7927. */
  7928. var Deferred = /** @class */ (function () {
  7929. /**
  7930. * Constructor for this deferred object.
  7931. */
  7932. function Deferred() {
  7933. var _this = this;
  7934. this.promise = new Promise(function (resolve, reject) {
  7935. _this._resolve = resolve;
  7936. _this._reject = reject;
  7937. });
  7938. }
  7939. Object.defineProperty(Deferred.prototype, "resolve", {
  7940. /**
  7941. * The resolve method of the promise associated with this deferred object.
  7942. */
  7943. get: function () {
  7944. return this._resolve;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Deferred.prototype, "reject", {
  7950. /**
  7951. * The reject method of the promise associated with this deferred object.
  7952. */
  7953. get: function () {
  7954. return this._reject;
  7955. },
  7956. enumerable: true,
  7957. configurable: true
  7958. });
  7959. return Deferred;
  7960. }());
  7961. BABYLON.Deferred = Deferred;
  7962. })(BABYLON || (BABYLON = {}));
  7963. //# sourceMappingURL=babylon.deferred.js.map
  7964. var BABYLON;
  7965. (function (BABYLON) {
  7966. /**
  7967. * A class serves as a medium between the observable and its observers
  7968. */
  7969. var EventState = /** @class */ (function () {
  7970. /**
  7971. * Create a new EventState
  7972. * @param mask defines the mask associated with this state
  7973. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7974. * @param target defines the original target of the state
  7975. * @param currentTarget defines the current target of the state
  7976. */
  7977. function EventState(mask, skipNextObservers, target, currentTarget) {
  7978. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7979. this.initalize(mask, skipNextObservers, target, currentTarget);
  7980. }
  7981. /**
  7982. * Initialize the current event state
  7983. * @param mask defines the mask associated with this state
  7984. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7985. * @param target defines the original target of the state
  7986. * @param currentTarget defines the current target of the state
  7987. * @returns the current event state
  7988. */
  7989. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7990. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7991. this.mask = mask;
  7992. this.skipNextObservers = skipNextObservers;
  7993. this.target = target;
  7994. this.currentTarget = currentTarget;
  7995. return this;
  7996. };
  7997. return EventState;
  7998. }());
  7999. BABYLON.EventState = EventState;
  8000. /**
  8001. * Represent an Observer registered to a given Observable object.
  8002. */
  8003. var Observer = /** @class */ (function () {
  8004. /**
  8005. * Creates a new observer
  8006. * @param callback defines the callback to call when the observer is notified
  8007. * @param mask defines the mask of the observer (used to filter notifications)
  8008. * @param scope defines the current scope used to restore the JS context
  8009. */
  8010. function Observer(
  8011. /**
  8012. * Defines the callback to call when the observer is notified
  8013. */
  8014. callback,
  8015. /**
  8016. * Defines the mask of the observer (used to filter notifications)
  8017. */
  8018. mask,
  8019. /**
  8020. * Defines the current scope used to restore the JS context
  8021. */
  8022. scope) {
  8023. if (scope === void 0) { scope = null; }
  8024. this.callback = callback;
  8025. this.mask = mask;
  8026. this.scope = scope;
  8027. /** @hidden */
  8028. this._willBeUnregistered = false;
  8029. /**
  8030. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8031. */
  8032. this.unregisterOnNextCall = false;
  8033. }
  8034. return Observer;
  8035. }());
  8036. BABYLON.Observer = Observer;
  8037. /**
  8038. * Represent a list of observers registered to multiple Observables object.
  8039. */
  8040. var MultiObserver = /** @class */ (function () {
  8041. function MultiObserver() {
  8042. }
  8043. /**
  8044. * Release associated resources
  8045. */
  8046. MultiObserver.prototype.dispose = function () {
  8047. if (this._observers && this._observables) {
  8048. for (var index = 0; index < this._observers.length; index++) {
  8049. this._observables[index].remove(this._observers[index]);
  8050. }
  8051. }
  8052. this._observers = null;
  8053. this._observables = null;
  8054. };
  8055. /**
  8056. * Raise a callback when one of the observable will notify
  8057. * @param observables defines a list of observables to watch
  8058. * @param callback defines the callback to call on notification
  8059. * @param mask defines the mask used to filter notifications
  8060. * @param scope defines the current scope used to restore the JS context
  8061. * @returns the new MultiObserver
  8062. */
  8063. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8064. if (mask === void 0) { mask = -1; }
  8065. if (scope === void 0) { scope = null; }
  8066. var result = new MultiObserver();
  8067. result._observers = new Array();
  8068. result._observables = observables;
  8069. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8070. var observable = observables_1[_i];
  8071. var observer = observable.add(callback, mask, false, scope);
  8072. if (observer) {
  8073. result._observers.push(observer);
  8074. }
  8075. }
  8076. return result;
  8077. };
  8078. return MultiObserver;
  8079. }());
  8080. BABYLON.MultiObserver = MultiObserver;
  8081. /**
  8082. * The Observable class is a simple implementation of the Observable pattern.
  8083. *
  8084. * 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.
  8085. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8086. * 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).
  8087. * 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.
  8088. */
  8089. var Observable = /** @class */ (function () {
  8090. /**
  8091. * Creates a new observable
  8092. * @param onObserverAdded defines a callback to call when a new observer is added
  8093. */
  8094. function Observable(onObserverAdded) {
  8095. this._observers = new Array();
  8096. this._eventState = new EventState(0);
  8097. if (onObserverAdded) {
  8098. this._onObserverAdded = onObserverAdded;
  8099. }
  8100. }
  8101. /**
  8102. * Create a new Observer with the specified callback
  8103. * @param callback the callback that will be executed for that Observer
  8104. * @param mask the mask used to filter observers
  8105. * @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.
  8106. * @param scope optional scope for the callback to be called from
  8107. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8108. * @returns the new observer created for the callback
  8109. */
  8110. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8111. if (mask === void 0) { mask = -1; }
  8112. if (insertFirst === void 0) { insertFirst = false; }
  8113. if (scope === void 0) { scope = null; }
  8114. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8115. if (!callback) {
  8116. return null;
  8117. }
  8118. var observer = new Observer(callback, mask, scope);
  8119. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8120. if (insertFirst) {
  8121. this._observers.unshift(observer);
  8122. }
  8123. else {
  8124. this._observers.push(observer);
  8125. }
  8126. if (this._onObserverAdded) {
  8127. this._onObserverAdded(observer);
  8128. }
  8129. return observer;
  8130. };
  8131. /**
  8132. * Remove an Observer from the Observable object
  8133. * @param observer the instance of the Observer to remove
  8134. * @returns false if it doesn't belong to this Observable
  8135. */
  8136. Observable.prototype.remove = function (observer) {
  8137. if (!observer) {
  8138. return false;
  8139. }
  8140. var index = this._observers.indexOf(observer);
  8141. if (index !== -1) {
  8142. this._observers.splice(index, 1);
  8143. return true;
  8144. }
  8145. return false;
  8146. };
  8147. /**
  8148. * Remove a callback from the Observable object
  8149. * @param callback the callback to remove
  8150. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8151. * @returns false if it doesn't belong to this Observable
  8152. */
  8153. Observable.prototype.removeCallback = function (callback, scope) {
  8154. for (var index = 0; index < this._observers.length; index++) {
  8155. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8156. this._observers.splice(index, 1);
  8157. return true;
  8158. }
  8159. }
  8160. return false;
  8161. };
  8162. Observable.prototype._deferUnregister = function (observer) {
  8163. var _this = this;
  8164. observer.unregisterOnNextCall = false;
  8165. observer._willBeUnregistered = true;
  8166. BABYLON.Tools.SetImmediate(function () {
  8167. _this.remove(observer);
  8168. });
  8169. };
  8170. /**
  8171. * Notify all Observers by calling their respective callback with the given data
  8172. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8173. * @param eventData defines the data to send to all observers
  8174. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8175. * @param target defines the original target of the state
  8176. * @param currentTarget defines the current target of the state
  8177. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8178. */
  8179. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8180. if (mask === void 0) { mask = -1; }
  8181. if (!this._observers.length) {
  8182. return true;
  8183. }
  8184. var state = this._eventState;
  8185. state.mask = mask;
  8186. state.target = target;
  8187. state.currentTarget = currentTarget;
  8188. state.skipNextObservers = false;
  8189. state.lastReturnValue = eventData;
  8190. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8191. var obs = _a[_i];
  8192. if (obs._willBeUnregistered) {
  8193. continue;
  8194. }
  8195. if (obs.mask & mask) {
  8196. if (obs.scope) {
  8197. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8198. }
  8199. else {
  8200. state.lastReturnValue = obs.callback(eventData, state);
  8201. }
  8202. if (obs.unregisterOnNextCall) {
  8203. this._deferUnregister(obs);
  8204. }
  8205. }
  8206. if (state.skipNextObservers) {
  8207. return false;
  8208. }
  8209. }
  8210. return true;
  8211. };
  8212. /**
  8213. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8214. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8215. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8216. * and it is crucial that all callbacks will be executed.
  8217. * The order of the callbacks is kept, callbacks are not executed parallel.
  8218. *
  8219. * @param eventData The data to be sent to each callback
  8220. * @param mask is used to filter observers defaults to -1
  8221. * @param target defines the callback target (see EventState)
  8222. * @param currentTarget defines he current object in the bubbling phase
  8223. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8224. */
  8225. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8226. var _this = this;
  8227. if (mask === void 0) { mask = -1; }
  8228. // create an empty promise
  8229. var p = Promise.resolve(eventData);
  8230. // no observers? return this promise.
  8231. if (!this._observers.length) {
  8232. return p;
  8233. }
  8234. var state = this._eventState;
  8235. state.mask = mask;
  8236. state.target = target;
  8237. state.currentTarget = currentTarget;
  8238. state.skipNextObservers = false;
  8239. // execute one callback after another (not using Promise.all, the order is important)
  8240. this._observers.forEach(function (obs) {
  8241. if (state.skipNextObservers) {
  8242. return;
  8243. }
  8244. if (obs._willBeUnregistered) {
  8245. return;
  8246. }
  8247. if (obs.mask & mask) {
  8248. if (obs.scope) {
  8249. p = p.then(function (lastReturnedValue) {
  8250. state.lastReturnValue = lastReturnedValue;
  8251. return obs.callback.apply(obs.scope, [eventData, state]);
  8252. });
  8253. }
  8254. else {
  8255. p = p.then(function (lastReturnedValue) {
  8256. state.lastReturnValue = lastReturnedValue;
  8257. return obs.callback(eventData, state);
  8258. });
  8259. }
  8260. if (obs.unregisterOnNextCall) {
  8261. _this._deferUnregister(obs);
  8262. }
  8263. }
  8264. });
  8265. // return the eventData
  8266. return p.then(function () { return eventData; });
  8267. };
  8268. /**
  8269. * Notify a specific observer
  8270. * @param observer defines the observer to notify
  8271. * @param eventData defines the data to be sent to each callback
  8272. * @param mask is used to filter observers defaults to -1
  8273. */
  8274. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8275. if (mask === void 0) { mask = -1; }
  8276. var state = this._eventState;
  8277. state.mask = mask;
  8278. state.skipNextObservers = false;
  8279. observer.callback(eventData, state);
  8280. };
  8281. /**
  8282. * Gets a boolean indicating if the observable has at least one observer
  8283. * @returns true is the Observable has at least one Observer registered
  8284. */
  8285. Observable.prototype.hasObservers = function () {
  8286. return this._observers.length > 0;
  8287. };
  8288. /**
  8289. * Clear the list of observers
  8290. */
  8291. Observable.prototype.clear = function () {
  8292. this._observers = new Array();
  8293. this._onObserverAdded = null;
  8294. };
  8295. /**
  8296. * Clone the current observable
  8297. * @returns a new observable
  8298. */
  8299. Observable.prototype.clone = function () {
  8300. var result = new Observable();
  8301. result._observers = this._observers.slice(0);
  8302. return result;
  8303. };
  8304. /**
  8305. * Does this observable handles observer registered with a given mask
  8306. * @param mask defines the mask to be tested
  8307. * @return whether or not one observer registered with the given mask is handeled
  8308. **/
  8309. Observable.prototype.hasSpecificMask = function (mask) {
  8310. if (mask === void 0) { mask = -1; }
  8311. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8312. var obs = _a[_i];
  8313. if (obs.mask & mask || obs.mask === mask) {
  8314. return true;
  8315. }
  8316. }
  8317. return false;
  8318. };
  8319. return Observable;
  8320. }());
  8321. BABYLON.Observable = Observable;
  8322. })(BABYLON || (BABYLON = {}));
  8323. //# sourceMappingURL=babylon.observable.js.map
  8324. var BABYLON;
  8325. (function (BABYLON) {
  8326. var SmartArray = /** @class */ (function () {
  8327. function SmartArray(capacity) {
  8328. this.length = 0;
  8329. this.data = new Array(capacity);
  8330. this._id = SmartArray._GlobalId++;
  8331. }
  8332. SmartArray.prototype.push = function (value) {
  8333. this.data[this.length++] = value;
  8334. if (this.length > this.data.length) {
  8335. this.data.length *= 2;
  8336. }
  8337. };
  8338. SmartArray.prototype.forEach = function (func) {
  8339. for (var index = 0; index < this.length; index++) {
  8340. func(this.data[index]);
  8341. }
  8342. };
  8343. SmartArray.prototype.sort = function (compareFn) {
  8344. this.data.sort(compareFn);
  8345. };
  8346. SmartArray.prototype.reset = function () {
  8347. this.length = 0;
  8348. };
  8349. SmartArray.prototype.dispose = function () {
  8350. this.reset();
  8351. if (this.data) {
  8352. this.data.length = 0;
  8353. this.data = [];
  8354. }
  8355. };
  8356. SmartArray.prototype.concat = function (array) {
  8357. if (array.length === 0) {
  8358. return;
  8359. }
  8360. if (this.length + array.length > this.data.length) {
  8361. this.data.length = (this.length + array.length) * 2;
  8362. }
  8363. for (var index = 0; index < array.length; index++) {
  8364. this.data[this.length++] = (array.data || array)[index];
  8365. }
  8366. };
  8367. SmartArray.prototype.indexOf = function (value) {
  8368. var position = this.data.indexOf(value);
  8369. if (position >= this.length) {
  8370. return -1;
  8371. }
  8372. return position;
  8373. };
  8374. SmartArray.prototype.contains = function (value) {
  8375. return this.data.indexOf(value) !== -1;
  8376. };
  8377. // Statics
  8378. SmartArray._GlobalId = 0;
  8379. return SmartArray;
  8380. }());
  8381. BABYLON.SmartArray = SmartArray;
  8382. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8383. __extends(SmartArrayNoDuplicate, _super);
  8384. function SmartArrayNoDuplicate() {
  8385. var _this = _super !== null && _super.apply(this, arguments) || this;
  8386. _this._duplicateId = 0;
  8387. return _this;
  8388. }
  8389. SmartArrayNoDuplicate.prototype.push = function (value) {
  8390. _super.prototype.push.call(this, value);
  8391. if (!value.__smartArrayFlags) {
  8392. value.__smartArrayFlags = {};
  8393. }
  8394. value.__smartArrayFlags[this._id] = this._duplicateId;
  8395. };
  8396. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8397. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8398. return false;
  8399. }
  8400. this.push(value);
  8401. return true;
  8402. };
  8403. SmartArrayNoDuplicate.prototype.reset = function () {
  8404. _super.prototype.reset.call(this);
  8405. this._duplicateId++;
  8406. };
  8407. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8408. if (array.length === 0) {
  8409. return;
  8410. }
  8411. if (this.length + array.length > this.data.length) {
  8412. this.data.length = (this.length + array.length) * 2;
  8413. }
  8414. for (var index = 0; index < array.length; index++) {
  8415. var item = (array.data || array)[index];
  8416. this.pushNoDuplicate(item);
  8417. }
  8418. };
  8419. return SmartArrayNoDuplicate;
  8420. }(SmartArray));
  8421. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8422. })(BABYLON || (BABYLON = {}));
  8423. //# sourceMappingURL=babylon.smartArray.js.map
  8424. var BABYLON;
  8425. (function (BABYLON) {
  8426. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8427. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8428. var LoadFileError = /** @class */ (function (_super) {
  8429. __extends(LoadFileError, _super);
  8430. function LoadFileError(message, request) {
  8431. var _this = _super.call(this, message) || this;
  8432. _this.request = request;
  8433. _this.name = "LoadFileError";
  8434. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8435. return _this;
  8436. }
  8437. // Polyfill for Object.setPrototypeOf if necessary.
  8438. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8439. return LoadFileError;
  8440. }(Error));
  8441. BABYLON.LoadFileError = LoadFileError;
  8442. var RetryStrategy = /** @class */ (function () {
  8443. function RetryStrategy() {
  8444. }
  8445. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8446. if (maxRetries === void 0) { maxRetries = 3; }
  8447. if (baseInterval === void 0) { baseInterval = 500; }
  8448. return function (url, request, retryIndex) {
  8449. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8450. return -1;
  8451. }
  8452. return Math.pow(2, retryIndex) * baseInterval;
  8453. };
  8454. };
  8455. return RetryStrategy;
  8456. }());
  8457. BABYLON.RetryStrategy = RetryStrategy;
  8458. // Screenshots
  8459. var screenshotCanvas;
  8460. var cloneValue = function (source, destinationObject) {
  8461. if (!source)
  8462. return null;
  8463. if (source instanceof BABYLON.Mesh) {
  8464. return null;
  8465. }
  8466. if (source instanceof BABYLON.SubMesh) {
  8467. return source.clone(destinationObject);
  8468. }
  8469. else if (source.clone) {
  8470. return source.clone();
  8471. }
  8472. return null;
  8473. };
  8474. var Tools = /** @class */ (function () {
  8475. function Tools() {
  8476. }
  8477. /**
  8478. * Interpolates between a and b via alpha
  8479. * @param a The lower value (returned when alpha = 0)
  8480. * @param b The upper value (returned when alpha = 1)
  8481. * @param alpha The interpolation-factor
  8482. * @return The mixed value
  8483. */
  8484. Tools.Mix = function (a, b, alpha) {
  8485. return a * (1 - alpha) + b * alpha;
  8486. };
  8487. Tools.Instantiate = function (className) {
  8488. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8489. return Tools.RegisteredExternalClasses[className];
  8490. }
  8491. var arr = className.split(".");
  8492. var fn = (window || this);
  8493. for (var i = 0, len = arr.length; i < len; i++) {
  8494. fn = fn[arr[i]];
  8495. }
  8496. if (typeof fn !== "function") {
  8497. return null;
  8498. }
  8499. return fn;
  8500. };
  8501. /**
  8502. * Provides a slice function that will work even on IE
  8503. * @param data defines the array to slice
  8504. * @param start defines the start of the data (optional)
  8505. * @param end defines the end of the data (optional)
  8506. * @returns the new sliced array
  8507. */
  8508. Tools.Slice = function (data, start, end) {
  8509. if (data.slice) {
  8510. return data.slice(start, end);
  8511. }
  8512. return Array.prototype.slice.call(data, start, end);
  8513. };
  8514. Tools.SetImmediate = function (action) {
  8515. if (window.setImmediate) {
  8516. window.setImmediate(action);
  8517. }
  8518. else {
  8519. setTimeout(action, 1);
  8520. }
  8521. };
  8522. Tools.IsExponentOfTwo = function (value) {
  8523. var count = 1;
  8524. do {
  8525. count *= 2;
  8526. } while (count < value);
  8527. return count === value;
  8528. };
  8529. /**
  8530. * Returns the nearest 32-bit single precision float representation of a Number
  8531. * @param value A Number. If the parameter is of a different type, it will get converted
  8532. * to a number or to NaN if it cannot be converted
  8533. * @returns number
  8534. */
  8535. Tools.FloatRound = function (value) {
  8536. if (Math.fround) {
  8537. return Math.fround(value);
  8538. }
  8539. return (Tools._tmpFloatArray[0] = value);
  8540. };
  8541. /**
  8542. * Find the next highest power of two.
  8543. * @param x Number to start search from.
  8544. * @return Next highest power of two.
  8545. */
  8546. Tools.CeilingPOT = function (x) {
  8547. x--;
  8548. x |= x >> 1;
  8549. x |= x >> 2;
  8550. x |= x >> 4;
  8551. x |= x >> 8;
  8552. x |= x >> 16;
  8553. x++;
  8554. return x;
  8555. };
  8556. /**
  8557. * Find the next lowest power of two.
  8558. * @param x Number to start search from.
  8559. * @return Next lowest power of two.
  8560. */
  8561. Tools.FloorPOT = function (x) {
  8562. x = x | (x >> 1);
  8563. x = x | (x >> 2);
  8564. x = x | (x >> 4);
  8565. x = x | (x >> 8);
  8566. x = x | (x >> 16);
  8567. return x - (x >> 1);
  8568. };
  8569. /**
  8570. * Find the nearest power of two.
  8571. * @param x Number to start search from.
  8572. * @return Next nearest power of two.
  8573. */
  8574. Tools.NearestPOT = function (x) {
  8575. var c = Tools.CeilingPOT(x);
  8576. var f = Tools.FloorPOT(x);
  8577. return (c - x) > (x - f) ? f : c;
  8578. };
  8579. Tools.GetExponentOfTwo = function (value, max, mode) {
  8580. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8581. var pot;
  8582. switch (mode) {
  8583. case BABYLON.Engine.SCALEMODE_FLOOR:
  8584. pot = Tools.FloorPOT(value);
  8585. break;
  8586. case BABYLON.Engine.SCALEMODE_NEAREST:
  8587. pot = Tools.NearestPOT(value);
  8588. break;
  8589. case BABYLON.Engine.SCALEMODE_CEILING:
  8590. default:
  8591. pot = Tools.CeilingPOT(value);
  8592. break;
  8593. }
  8594. return Math.min(pot, max);
  8595. };
  8596. Tools.GetFilename = function (path) {
  8597. var index = path.lastIndexOf("/");
  8598. if (index < 0)
  8599. return path;
  8600. return path.substring(index + 1);
  8601. };
  8602. /**
  8603. * Extracts the "folder" part of a path (everything before the filename).
  8604. * @param uri The URI to extract the info from
  8605. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8606. * @returns The "folder" part of the path
  8607. */
  8608. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8609. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8610. var index = uri.lastIndexOf("/");
  8611. if (index < 0) {
  8612. if (returnUnchangedIfNoSlash) {
  8613. return uri;
  8614. }
  8615. return "";
  8616. }
  8617. return uri.substring(0, index + 1);
  8618. };
  8619. Tools.GetDOMTextContent = function (element) {
  8620. var result = "";
  8621. var child = element.firstChild;
  8622. while (child) {
  8623. if (child.nodeType === 3) {
  8624. result += child.textContent;
  8625. }
  8626. child = child.nextSibling;
  8627. }
  8628. return result;
  8629. };
  8630. Tools.ToDegrees = function (angle) {
  8631. return angle * 180 / Math.PI;
  8632. };
  8633. Tools.ToRadians = function (angle) {
  8634. return angle * Math.PI / 180;
  8635. };
  8636. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8637. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8638. var output = "";
  8639. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8640. var i = 0;
  8641. var bytes = new Uint8Array(buffer);
  8642. while (i < bytes.length) {
  8643. chr1 = bytes[i++];
  8644. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8645. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8646. enc1 = chr1 >> 2;
  8647. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8648. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8649. enc4 = chr3 & 63;
  8650. if (isNaN(chr2)) {
  8651. enc3 = enc4 = 64;
  8652. }
  8653. else if (isNaN(chr3)) {
  8654. enc4 = 64;
  8655. }
  8656. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8657. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8658. }
  8659. return "data:image/png;base64," + output;
  8660. };
  8661. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8662. if (bias === void 0) { bias = null; }
  8663. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8664. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8665. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8666. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8667. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8668. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8669. }
  8670. if (bias) {
  8671. minimum.x -= minimum.x * bias.x + bias.y;
  8672. minimum.y -= minimum.y * bias.x + bias.y;
  8673. minimum.z -= minimum.z * bias.x + bias.y;
  8674. maximum.x += maximum.x * bias.x + bias.y;
  8675. maximum.y += maximum.y * bias.x + bias.y;
  8676. maximum.z += maximum.z * bias.x + bias.y;
  8677. }
  8678. return {
  8679. minimum: minimum,
  8680. maximum: maximum
  8681. };
  8682. };
  8683. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8684. if (bias === void 0) { bias = null; }
  8685. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8686. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8687. if (!stride) {
  8688. stride = 3;
  8689. }
  8690. for (var index = start; index < start + count; index++) {
  8691. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8692. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8693. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8694. }
  8695. if (bias) {
  8696. minimum.x -= minimum.x * bias.x + bias.y;
  8697. minimum.y -= minimum.y * bias.x + bias.y;
  8698. minimum.z -= minimum.z * bias.x + bias.y;
  8699. maximum.x += maximum.x * bias.x + bias.y;
  8700. maximum.y += maximum.y * bias.x + bias.y;
  8701. maximum.z += maximum.z * bias.x + bias.y;
  8702. }
  8703. return {
  8704. minimum: minimum,
  8705. maximum: maximum
  8706. };
  8707. };
  8708. Tools.Vector2ArrayFeeder = function (array) {
  8709. return function (index) {
  8710. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8711. var length = isFloatArray ? array.length / 2 : array.length;
  8712. if (index >= length) {
  8713. return null;
  8714. }
  8715. if (isFloatArray) {
  8716. var fa = array;
  8717. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8718. }
  8719. var a = array;
  8720. return a[index];
  8721. };
  8722. };
  8723. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8724. if (bias === void 0) { bias = null; }
  8725. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8726. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8727. var i = 0;
  8728. var cur = feeder(i++);
  8729. while (cur) {
  8730. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8731. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8732. cur = feeder(i++);
  8733. }
  8734. if (bias) {
  8735. minimum.x -= minimum.x * bias.x + bias.y;
  8736. minimum.y -= minimum.y * bias.x + bias.y;
  8737. maximum.x += maximum.x * bias.x + bias.y;
  8738. maximum.y += maximum.y * bias.x + bias.y;
  8739. }
  8740. return {
  8741. minimum: minimum,
  8742. maximum: maximum
  8743. };
  8744. };
  8745. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8746. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8747. return null;
  8748. return Array.isArray(obj) ? obj : [obj];
  8749. };
  8750. // Misc.
  8751. Tools.GetPointerPrefix = function () {
  8752. var eventPrefix = "pointer";
  8753. // Check if pointer events are supported
  8754. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8755. eventPrefix = "mouse";
  8756. }
  8757. return eventPrefix;
  8758. };
  8759. /**
  8760. * @param func - the function to be called
  8761. * @param requester - the object that will request the next frame. Falls back to window.
  8762. */
  8763. Tools.QueueNewFrame = function (func, requester) {
  8764. if (!Tools.IsWindowObjectExist()) {
  8765. return setTimeout(func, 16);
  8766. }
  8767. if (!requester) {
  8768. requester = window;
  8769. }
  8770. if (requester.requestAnimationFrame) {
  8771. return requester.requestAnimationFrame(func);
  8772. }
  8773. else if (requester.msRequestAnimationFrame) {
  8774. return requester.msRequestAnimationFrame(func);
  8775. }
  8776. else if (requester.webkitRequestAnimationFrame) {
  8777. return requester.webkitRequestAnimationFrame(func);
  8778. }
  8779. else if (requester.mozRequestAnimationFrame) {
  8780. return requester.mozRequestAnimationFrame(func);
  8781. }
  8782. else if (requester.oRequestAnimationFrame) {
  8783. return requester.oRequestAnimationFrame(func);
  8784. }
  8785. else {
  8786. return window.setTimeout(func, 16);
  8787. }
  8788. };
  8789. Tools.RequestFullscreen = function (element) {
  8790. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8791. if (!requestFunction)
  8792. return;
  8793. requestFunction.call(element);
  8794. };
  8795. Tools.ExitFullscreen = function () {
  8796. if (document.exitFullscreen) {
  8797. document.exitFullscreen();
  8798. }
  8799. else if (document.mozCancelFullScreen) {
  8800. document.mozCancelFullScreen();
  8801. }
  8802. else if (document.webkitCancelFullScreen) {
  8803. document.webkitCancelFullScreen();
  8804. }
  8805. else if (document.msCancelFullScreen) {
  8806. document.msCancelFullScreen();
  8807. }
  8808. };
  8809. Tools.SetCorsBehavior = function (url, element) {
  8810. if (url && url.indexOf("data:") === 0) {
  8811. return;
  8812. }
  8813. if (Tools.CorsBehavior) {
  8814. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8815. element.crossOrigin = Tools.CorsBehavior;
  8816. }
  8817. else {
  8818. var result = Tools.CorsBehavior(url);
  8819. if (result) {
  8820. element.crossOrigin = result;
  8821. }
  8822. }
  8823. }
  8824. };
  8825. // External files
  8826. Tools.CleanUrl = function (url) {
  8827. url = url.replace(/#/mg, "%23");
  8828. return url;
  8829. };
  8830. Tools.LoadImage = function (url, onLoad, onError, database) {
  8831. if (url instanceof ArrayBuffer) {
  8832. url = Tools.EncodeArrayBufferTobase64(url);
  8833. }
  8834. url = Tools.CleanUrl(url);
  8835. url = Tools.PreprocessUrl(url);
  8836. var img = new Image();
  8837. Tools.SetCorsBehavior(url, img);
  8838. var loadHandler = function () {
  8839. img.removeEventListener("load", loadHandler);
  8840. img.removeEventListener("error", errorHandler);
  8841. onLoad(img);
  8842. };
  8843. var errorHandler = function (err) {
  8844. img.removeEventListener("load", loadHandler);
  8845. img.removeEventListener("error", errorHandler);
  8846. Tools.Error("Error while trying to load image: " + url);
  8847. if (onError) {
  8848. onError("Error while trying to load image: " + url, err);
  8849. }
  8850. };
  8851. img.addEventListener("load", loadHandler);
  8852. img.addEventListener("error", errorHandler);
  8853. var noIndexedDB = function () {
  8854. img.src = url;
  8855. };
  8856. var loadFromIndexedDB = function () {
  8857. if (database) {
  8858. database.loadImageFromDB(url, img);
  8859. }
  8860. };
  8861. //ANY database to do!
  8862. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8863. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8864. }
  8865. else {
  8866. if (url.indexOf("file:") !== -1) {
  8867. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8868. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8869. try {
  8870. var blobURL;
  8871. try {
  8872. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8873. }
  8874. catch (ex) {
  8875. // Chrome doesn't support oneTimeOnly parameter
  8876. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8877. }
  8878. img.src = blobURL;
  8879. }
  8880. catch (e) {
  8881. img.src = "";
  8882. }
  8883. return img;
  8884. }
  8885. }
  8886. noIndexedDB();
  8887. }
  8888. return img;
  8889. };
  8890. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8891. url = Tools.CleanUrl(url);
  8892. url = Tools.PreprocessUrl(url);
  8893. // If file and file input are set
  8894. if (url.indexOf("file:") !== -1) {
  8895. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8896. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8897. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8898. }
  8899. }
  8900. var loadUrl = Tools.BaseUrl + url;
  8901. var aborted = false;
  8902. var fileRequest = {
  8903. onCompleteObservable: new BABYLON.Observable(),
  8904. abort: function () { return aborted = true; },
  8905. };
  8906. var requestFile = function () {
  8907. var request = new XMLHttpRequest();
  8908. var retryHandle = null;
  8909. fileRequest.abort = function () {
  8910. aborted = true;
  8911. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8912. request.abort();
  8913. }
  8914. if (retryHandle !== null) {
  8915. clearTimeout(retryHandle);
  8916. retryHandle = null;
  8917. }
  8918. };
  8919. var retryLoop = function (retryIndex) {
  8920. request.open('GET', loadUrl, true);
  8921. if (useArrayBuffer) {
  8922. request.responseType = "arraybuffer";
  8923. }
  8924. if (onProgress) {
  8925. request.addEventListener("progress", onProgress);
  8926. }
  8927. var onLoadEnd = function () {
  8928. request.removeEventListener("loadend", onLoadEnd);
  8929. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8930. fileRequest.onCompleteObservable.clear();
  8931. };
  8932. request.addEventListener("loadend", onLoadEnd);
  8933. var onReadyStateChange = function () {
  8934. if (aborted) {
  8935. return;
  8936. }
  8937. // In case of undefined state in some browsers.
  8938. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8939. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8940. request.removeEventListener("readystatechange", onReadyStateChange);
  8941. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8942. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8943. return;
  8944. }
  8945. var retryStrategy = Tools.DefaultRetryStrategy;
  8946. if (retryStrategy) {
  8947. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8948. if (waitTime !== -1) {
  8949. // Prevent the request from completing for retry.
  8950. request.removeEventListener("loadend", onLoadEnd);
  8951. request = new XMLHttpRequest();
  8952. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8953. return;
  8954. }
  8955. }
  8956. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8957. if (onError) {
  8958. onError(request, e);
  8959. }
  8960. else {
  8961. throw e;
  8962. }
  8963. }
  8964. };
  8965. request.addEventListener("readystatechange", onReadyStateChange);
  8966. request.send();
  8967. };
  8968. retryLoop(0);
  8969. };
  8970. // Caching all files
  8971. if (database && database.enableSceneOffline) {
  8972. var noIndexedDB_1 = function () {
  8973. if (!aborted) {
  8974. requestFile();
  8975. }
  8976. };
  8977. var loadFromIndexedDB = function () {
  8978. // TODO: database needs to support aborting and should return a IFileRequest
  8979. if (aborted) {
  8980. return;
  8981. }
  8982. if (database) {
  8983. database.loadFileFromDB(url, function (data) {
  8984. if (!aborted) {
  8985. onSuccess(data);
  8986. }
  8987. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8988. }, onProgress ? function (event) {
  8989. if (!aborted) {
  8990. onProgress(event);
  8991. }
  8992. } : undefined, noIndexedDB_1, useArrayBuffer);
  8993. }
  8994. };
  8995. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8996. }
  8997. else {
  8998. requestFile();
  8999. }
  9000. return fileRequest;
  9001. };
  9002. /**
  9003. * Load a script (identified by an url). When the url returns, the
  9004. * content of this file is added into a new script element, attached to the DOM (body element)
  9005. */
  9006. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9007. var head = document.getElementsByTagName('head')[0];
  9008. var script = document.createElement('script');
  9009. script.type = 'text/javascript';
  9010. script.src = scriptUrl;
  9011. script.onload = function () {
  9012. if (onSuccess) {
  9013. onSuccess();
  9014. }
  9015. };
  9016. script.onerror = function (e) {
  9017. if (onError) {
  9018. onError("Unable to load script '" + scriptUrl + "'", e);
  9019. }
  9020. };
  9021. head.appendChild(script);
  9022. };
  9023. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9024. var reader = new FileReader();
  9025. var request = {
  9026. onCompleteObservable: new BABYLON.Observable(),
  9027. abort: function () { return reader.abort(); },
  9028. };
  9029. reader.onloadend = function (e) {
  9030. request.onCompleteObservable.notifyObservers(request);
  9031. };
  9032. reader.onload = function (e) {
  9033. //target doesn't have result from ts 1.3
  9034. callback(e.target['result']);
  9035. };
  9036. reader.onprogress = progressCallback;
  9037. reader.readAsDataURL(fileToLoad);
  9038. return request;
  9039. };
  9040. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9041. var reader = new FileReader();
  9042. var request = {
  9043. onCompleteObservable: new BABYLON.Observable(),
  9044. abort: function () { return reader.abort(); },
  9045. };
  9046. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9047. reader.onerror = function (e) {
  9048. Tools.Log("Error while reading file: " + fileToLoad.name);
  9049. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9050. };
  9051. reader.onload = function (e) {
  9052. //target doesn't have result from ts 1.3
  9053. callback(e.target['result']);
  9054. };
  9055. if (progressCallBack) {
  9056. reader.onprogress = progressCallBack;
  9057. }
  9058. if (!useArrayBuffer) {
  9059. // Asynchronous read
  9060. reader.readAsText(fileToLoad);
  9061. }
  9062. else {
  9063. reader.readAsArrayBuffer(fileToLoad);
  9064. }
  9065. return request;
  9066. };
  9067. //returns a downloadable url to a file content.
  9068. Tools.FileAsURL = function (content) {
  9069. var fileBlob = new Blob([content]);
  9070. var url = window.URL || window.webkitURL;
  9071. var link = url.createObjectURL(fileBlob);
  9072. return link;
  9073. };
  9074. // Misc.
  9075. Tools.Format = function (value, decimals) {
  9076. if (decimals === void 0) { decimals = 2; }
  9077. return value.toFixed(decimals);
  9078. };
  9079. Tools.CheckExtends = function (v, min, max) {
  9080. if (v.x < min.x)
  9081. min.x = v.x;
  9082. if (v.y < min.y)
  9083. min.y = v.y;
  9084. if (v.z < min.z)
  9085. min.z = v.z;
  9086. if (v.x > max.x)
  9087. max.x = v.x;
  9088. if (v.y > max.y)
  9089. max.y = v.y;
  9090. if (v.z > max.z)
  9091. max.z = v.z;
  9092. };
  9093. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9094. for (var prop in source) {
  9095. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9096. continue;
  9097. }
  9098. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9099. continue;
  9100. }
  9101. var sourceValue = source[prop];
  9102. var typeOfSourceValue = typeof sourceValue;
  9103. if (typeOfSourceValue === "function") {
  9104. continue;
  9105. }
  9106. try {
  9107. if (typeOfSourceValue === "object") {
  9108. if (sourceValue instanceof Array) {
  9109. destination[prop] = [];
  9110. if (sourceValue.length > 0) {
  9111. if (typeof sourceValue[0] == "object") {
  9112. for (var index = 0; index < sourceValue.length; index++) {
  9113. var clonedValue = cloneValue(sourceValue[index], destination);
  9114. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9115. destination[prop].push(clonedValue);
  9116. }
  9117. }
  9118. }
  9119. else {
  9120. destination[prop] = sourceValue.slice(0);
  9121. }
  9122. }
  9123. }
  9124. else {
  9125. destination[prop] = cloneValue(sourceValue, destination);
  9126. }
  9127. }
  9128. else {
  9129. destination[prop] = sourceValue;
  9130. }
  9131. }
  9132. catch (e) {
  9133. // Just ignore error (it could be because of a read-only property)
  9134. }
  9135. }
  9136. };
  9137. Tools.IsEmpty = function (obj) {
  9138. for (var i in obj) {
  9139. if (obj.hasOwnProperty(i)) {
  9140. return false;
  9141. }
  9142. }
  9143. return true;
  9144. };
  9145. Tools.RegisterTopRootEvents = function (events) {
  9146. for (var index = 0; index < events.length; index++) {
  9147. var event = events[index];
  9148. window.addEventListener(event.name, event.handler, false);
  9149. try {
  9150. if (window.parent) {
  9151. window.parent.addEventListener(event.name, event.handler, false);
  9152. }
  9153. }
  9154. catch (e) {
  9155. // Silently fails...
  9156. }
  9157. }
  9158. };
  9159. Tools.UnregisterTopRootEvents = function (events) {
  9160. for (var index = 0; index < events.length; index++) {
  9161. var event = events[index];
  9162. window.removeEventListener(event.name, event.handler);
  9163. try {
  9164. if (window.parent) {
  9165. window.parent.removeEventListener(event.name, event.handler);
  9166. }
  9167. }
  9168. catch (e) {
  9169. // Silently fails...
  9170. }
  9171. }
  9172. };
  9173. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9174. if (mimeType === void 0) { mimeType = "image/png"; }
  9175. // Read the contents of the framebuffer
  9176. var numberOfChannelsByLine = width * 4;
  9177. var halfHeight = height / 2;
  9178. //Reading datas from WebGL
  9179. var data = engine.readPixels(0, 0, width, height);
  9180. //To flip image on Y axis.
  9181. for (var i = 0; i < halfHeight; i++) {
  9182. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9183. var currentCell = j + i * numberOfChannelsByLine;
  9184. var targetLine = height - i - 1;
  9185. var targetCell = j + targetLine * numberOfChannelsByLine;
  9186. var temp = data[currentCell];
  9187. data[currentCell] = data[targetCell];
  9188. data[targetCell] = temp;
  9189. }
  9190. }
  9191. // Create a 2D canvas to store the result
  9192. if (!screenshotCanvas) {
  9193. screenshotCanvas = document.createElement('canvas');
  9194. }
  9195. screenshotCanvas.width = width;
  9196. screenshotCanvas.height = height;
  9197. var context = screenshotCanvas.getContext('2d');
  9198. if (context) {
  9199. // Copy the pixels to a 2D canvas
  9200. var imageData = context.createImageData(width, height);
  9201. var castData = (imageData.data);
  9202. castData.set(data);
  9203. context.putImageData(imageData, 0, 0);
  9204. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9205. }
  9206. };
  9207. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9208. if (mimeType === void 0) { mimeType = "image/png"; }
  9209. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9210. if (successCallback) {
  9211. successCallback(base64Image);
  9212. }
  9213. else {
  9214. // We need HTMLCanvasElement.toBlob for HD screenshots
  9215. if (!screenshotCanvas.toBlob) {
  9216. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9217. screenshotCanvas.toBlob = function (callback, type, quality) {
  9218. var _this = this;
  9219. setTimeout(function () {
  9220. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9221. for (var i = 0; i < len; i++) {
  9222. arr[i] = binStr.charCodeAt(i);
  9223. }
  9224. callback(new Blob([arr], { type: type || 'image/png' }));
  9225. });
  9226. };
  9227. }
  9228. screenshotCanvas.toBlob(function (blob) {
  9229. var url = URL.createObjectURL(blob);
  9230. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9231. if (("download" in document.createElement("a"))) {
  9232. var a = window.document.createElement("a");
  9233. a.href = url;
  9234. if (fileName) {
  9235. a.setAttribute("download", fileName);
  9236. }
  9237. else {
  9238. var date = new Date();
  9239. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9240. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9241. }
  9242. window.document.body.appendChild(a);
  9243. a.addEventListener("click", function () {
  9244. if (a.parentElement) {
  9245. a.parentElement.removeChild(a);
  9246. }
  9247. });
  9248. a.click();
  9249. }
  9250. else {
  9251. var newWindow = window.open("");
  9252. if (!newWindow)
  9253. return;
  9254. var img = newWindow.document.createElement("img");
  9255. img.onload = function () {
  9256. // no longer need to read the blob so it's revoked
  9257. URL.revokeObjectURL(url);
  9258. };
  9259. img.src = url;
  9260. newWindow.document.body.appendChild(img);
  9261. }
  9262. });
  9263. }
  9264. };
  9265. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9266. if (mimeType === void 0) { mimeType = "image/png"; }
  9267. var width;
  9268. var height;
  9269. // If a precision value is specified
  9270. if (size.precision) {
  9271. width = Math.round(engine.getRenderWidth() * size.precision);
  9272. height = Math.round(width / engine.getAspectRatio(camera));
  9273. }
  9274. else if (size.width && size.height) {
  9275. width = size.width;
  9276. height = size.height;
  9277. }
  9278. //If passing only width, computing height to keep display canvas ratio.
  9279. else if (size.width && !size.height) {
  9280. width = size.width;
  9281. height = Math.round(width / engine.getAspectRatio(camera));
  9282. }
  9283. //If passing only height, computing width to keep display canvas ratio.
  9284. else if (size.height && !size.width) {
  9285. height = size.height;
  9286. width = Math.round(height * engine.getAspectRatio(camera));
  9287. }
  9288. //Assuming here that "size" parameter is a number
  9289. else if (!isNaN(size)) {
  9290. height = size;
  9291. width = size;
  9292. }
  9293. else {
  9294. Tools.Error("Invalid 'size' parameter !");
  9295. return;
  9296. }
  9297. if (!screenshotCanvas) {
  9298. screenshotCanvas = document.createElement('canvas');
  9299. }
  9300. screenshotCanvas.width = width;
  9301. screenshotCanvas.height = height;
  9302. var renderContext = screenshotCanvas.getContext("2d");
  9303. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9304. var newWidth = width;
  9305. var newHeight = newWidth / ratio;
  9306. if (newHeight > height) {
  9307. newHeight = height;
  9308. newWidth = newHeight * ratio;
  9309. }
  9310. var offsetX = Math.max(0, width - newWidth) / 2;
  9311. var offsetY = Math.max(0, height - newHeight) / 2;
  9312. var renderingCanvas = engine.getRenderingCanvas();
  9313. if (renderContext && renderingCanvas) {
  9314. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9315. }
  9316. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9317. };
  9318. /**
  9319. * Generates an image screenshot from the specified camera.
  9320. *
  9321. * @param engine The engine to use for rendering
  9322. * @param camera The camera to use for rendering
  9323. * @param size This parameter can be set to a single number or to an object with the
  9324. * following (optional) properties: precision, width, height. If a single number is passed,
  9325. * it will be used for both width and height. If an object is passed, the screenshot size
  9326. * will be derived from the parameters. The precision property is a multiplier allowing
  9327. * rendering at a higher or lower resolution.
  9328. * @param successCallback The callback receives a single parameter which contains the
  9329. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9330. * src parameter of an <img> to display it.
  9331. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9332. * Check your browser for supported MIME types.
  9333. * @param samples Texture samples (default: 1)
  9334. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9335. * @param fileName A name for for the downloaded file.
  9336. * @constructor
  9337. */
  9338. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9339. if (mimeType === void 0) { mimeType = "image/png"; }
  9340. if (samples === void 0) { samples = 1; }
  9341. if (antialiasing === void 0) { antialiasing = false; }
  9342. var width;
  9343. var height;
  9344. //If a precision value is specified
  9345. if (size.precision) {
  9346. width = Math.round(engine.getRenderWidth() * size.precision);
  9347. height = Math.round(width / engine.getAspectRatio(camera));
  9348. size = { width: width, height: height };
  9349. }
  9350. else if (size.width && size.height) {
  9351. width = size.width;
  9352. height = size.height;
  9353. }
  9354. //If passing only width, computing height to keep display canvas ratio.
  9355. else if (size.width && !size.height) {
  9356. width = size.width;
  9357. height = Math.round(width / engine.getAspectRatio(camera));
  9358. size = { width: width, height: height };
  9359. }
  9360. //If passing only height, computing width to keep display canvas ratio.
  9361. else if (size.height && !size.width) {
  9362. height = size.height;
  9363. width = Math.round(height * engine.getAspectRatio(camera));
  9364. size = { width: width, height: height };
  9365. }
  9366. //Assuming here that "size" parameter is a number
  9367. else if (!isNaN(size)) {
  9368. height = size;
  9369. width = size;
  9370. }
  9371. else {
  9372. Tools.Error("Invalid 'size' parameter !");
  9373. return;
  9374. }
  9375. var scene = camera.getScene();
  9376. var previousCamera = null;
  9377. if (scene.activeCamera !== camera) {
  9378. previousCamera = scene.activeCamera;
  9379. scene.activeCamera = camera;
  9380. }
  9381. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9382. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9383. texture.renderList = null;
  9384. texture.samples = samples;
  9385. if (antialiasing) {
  9386. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9387. }
  9388. texture.onAfterRenderObservable.add(function () {
  9389. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9390. });
  9391. scene.incrementRenderId();
  9392. scene.resetCachedMaterial();
  9393. texture.render(true);
  9394. texture.dispose();
  9395. if (previousCamera) {
  9396. scene.activeCamera = previousCamera;
  9397. }
  9398. camera.getProjectionMatrix(true); // Force cache refresh;
  9399. };
  9400. // XHR response validator for local file scenario
  9401. Tools.ValidateXHRData = function (xhr, dataType) {
  9402. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9403. if (dataType === void 0) { dataType = 7; }
  9404. try {
  9405. if (dataType & 1) {
  9406. if (xhr.responseText && xhr.responseText.length > 0) {
  9407. return true;
  9408. }
  9409. else if (dataType === 1) {
  9410. return false;
  9411. }
  9412. }
  9413. if (dataType & 2) {
  9414. // Check header width and height since there is no "TGA" magic number
  9415. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9416. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9417. return true;
  9418. }
  9419. else if (dataType === 2) {
  9420. return false;
  9421. }
  9422. }
  9423. if (dataType & 4) {
  9424. // Check for the "DDS" magic number
  9425. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9426. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9427. return true;
  9428. }
  9429. else {
  9430. return false;
  9431. }
  9432. }
  9433. }
  9434. catch (e) {
  9435. // Global protection
  9436. }
  9437. return false;
  9438. };
  9439. /**
  9440. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9441. * Be aware Math.random() could cause collisions, but:
  9442. * "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"
  9443. */
  9444. Tools.RandomId = function () {
  9445. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9446. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9447. return v.toString(16);
  9448. });
  9449. };
  9450. /**
  9451. * Test if the given uri is a base64 string.
  9452. * @param uri The uri to test
  9453. * @return True if the uri is a base64 string or false otherwise.
  9454. */
  9455. Tools.IsBase64 = function (uri) {
  9456. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9457. };
  9458. /**
  9459. * Decode the given base64 uri.
  9460. * @param uri The uri to decode
  9461. * @return The decoded base64 data.
  9462. */
  9463. Tools.DecodeBase64 = function (uri) {
  9464. var decodedString = atob(uri.split(",")[1]);
  9465. var bufferLength = decodedString.length;
  9466. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9467. for (var i = 0; i < bufferLength; i++) {
  9468. bufferView[i] = decodedString.charCodeAt(i);
  9469. }
  9470. return bufferView.buffer;
  9471. };
  9472. Object.defineProperty(Tools, "NoneLogLevel", {
  9473. get: function () {
  9474. return Tools._NoneLogLevel;
  9475. },
  9476. enumerable: true,
  9477. configurable: true
  9478. });
  9479. Object.defineProperty(Tools, "MessageLogLevel", {
  9480. get: function () {
  9481. return Tools._MessageLogLevel;
  9482. },
  9483. enumerable: true,
  9484. configurable: true
  9485. });
  9486. Object.defineProperty(Tools, "WarningLogLevel", {
  9487. get: function () {
  9488. return Tools._WarningLogLevel;
  9489. },
  9490. enumerable: true,
  9491. configurable: true
  9492. });
  9493. Object.defineProperty(Tools, "ErrorLogLevel", {
  9494. get: function () {
  9495. return Tools._ErrorLogLevel;
  9496. },
  9497. enumerable: true,
  9498. configurable: true
  9499. });
  9500. Object.defineProperty(Tools, "AllLogLevel", {
  9501. get: function () {
  9502. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9503. },
  9504. enumerable: true,
  9505. configurable: true
  9506. });
  9507. Tools._AddLogEntry = function (entry) {
  9508. Tools._LogCache = entry + Tools._LogCache;
  9509. if (Tools.OnNewCacheEntry) {
  9510. Tools.OnNewCacheEntry(entry);
  9511. }
  9512. };
  9513. Tools._FormatMessage = function (message) {
  9514. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9515. var date = new Date();
  9516. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9517. };
  9518. Tools._LogDisabled = function (message) {
  9519. // nothing to do
  9520. };
  9521. Tools._LogEnabled = function (message) {
  9522. var formattedMessage = Tools._FormatMessage(message);
  9523. console.log("BJS - " + formattedMessage);
  9524. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9525. Tools._AddLogEntry(entry);
  9526. };
  9527. Tools._WarnDisabled = function (message) {
  9528. // nothing to do
  9529. };
  9530. Tools._WarnEnabled = function (message) {
  9531. var formattedMessage = Tools._FormatMessage(message);
  9532. console.warn("BJS - " + formattedMessage);
  9533. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9534. Tools._AddLogEntry(entry);
  9535. };
  9536. Tools._ErrorDisabled = function (message) {
  9537. // nothing to do
  9538. };
  9539. Tools._ErrorEnabled = function (message) {
  9540. Tools.errorsCount++;
  9541. var formattedMessage = Tools._FormatMessage(message);
  9542. console.error("BJS - " + formattedMessage);
  9543. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9544. Tools._AddLogEntry(entry);
  9545. };
  9546. Object.defineProperty(Tools, "LogCache", {
  9547. get: function () {
  9548. return Tools._LogCache;
  9549. },
  9550. enumerable: true,
  9551. configurable: true
  9552. });
  9553. Tools.ClearLogCache = function () {
  9554. Tools._LogCache = "";
  9555. Tools.errorsCount = 0;
  9556. };
  9557. Object.defineProperty(Tools, "LogLevels", {
  9558. set: function (level) {
  9559. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9560. Tools.Log = Tools._LogEnabled;
  9561. }
  9562. else {
  9563. Tools.Log = Tools._LogDisabled;
  9564. }
  9565. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9566. Tools.Warn = Tools._WarnEnabled;
  9567. }
  9568. else {
  9569. Tools.Warn = Tools._WarnDisabled;
  9570. }
  9571. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9572. Tools.Error = Tools._ErrorEnabled;
  9573. }
  9574. else {
  9575. Tools.Error = Tools._ErrorDisabled;
  9576. }
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Tools.IsWindowObjectExist = function () {
  9582. return (typeof window) !== "undefined";
  9583. };
  9584. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9585. get: function () {
  9586. return Tools._PerformanceNoneLogLevel;
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9592. get: function () {
  9593. return Tools._PerformanceUserMarkLogLevel;
  9594. },
  9595. enumerable: true,
  9596. configurable: true
  9597. });
  9598. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9599. get: function () {
  9600. return Tools._PerformanceConsoleLogLevel;
  9601. },
  9602. enumerable: true,
  9603. configurable: true
  9604. });
  9605. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9606. set: function (level) {
  9607. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9608. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9609. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9610. return;
  9611. }
  9612. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9613. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9614. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9615. return;
  9616. }
  9617. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9618. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9624. };
  9625. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9626. };
  9627. Tools._StartUserMark = function (counterName, condition) {
  9628. if (condition === void 0) { condition = true; }
  9629. if (!Tools._performance) {
  9630. if (!Tools.IsWindowObjectExist()) {
  9631. return;
  9632. }
  9633. Tools._performance = window.performance;
  9634. }
  9635. if (!condition || !Tools._performance.mark) {
  9636. return;
  9637. }
  9638. Tools._performance.mark(counterName + "-Begin");
  9639. };
  9640. Tools._EndUserMark = function (counterName, condition) {
  9641. if (condition === void 0) { condition = true; }
  9642. if (!condition || !Tools._performance.mark) {
  9643. return;
  9644. }
  9645. Tools._performance.mark(counterName + "-End");
  9646. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9647. };
  9648. Tools._StartPerformanceConsole = function (counterName, condition) {
  9649. if (condition === void 0) { condition = true; }
  9650. if (!condition) {
  9651. return;
  9652. }
  9653. Tools._StartUserMark(counterName, condition);
  9654. if (console.time) {
  9655. console.time(counterName);
  9656. }
  9657. };
  9658. Tools._EndPerformanceConsole = function (counterName, condition) {
  9659. if (condition === void 0) { condition = true; }
  9660. if (!condition) {
  9661. return;
  9662. }
  9663. Tools._EndUserMark(counterName, condition);
  9664. if (console.time) {
  9665. console.timeEnd(counterName);
  9666. }
  9667. };
  9668. Object.defineProperty(Tools, "Now", {
  9669. get: function () {
  9670. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9671. return window.performance.now();
  9672. }
  9673. return Date.now();
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. /**
  9679. * This method will return the name of the class used to create the instance of the given object.
  9680. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9681. * @param object the object to get the class name from
  9682. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9683. */
  9684. Tools.GetClassName = function (object, isType) {
  9685. if (isType === void 0) { isType = false; }
  9686. var name = null;
  9687. if (!isType && object.getClassName) {
  9688. name = object.getClassName();
  9689. }
  9690. else {
  9691. if (object instanceof Object) {
  9692. var classObj = isType ? object : Object.getPrototypeOf(object);
  9693. name = classObj.constructor["__bjsclassName__"];
  9694. }
  9695. if (!name) {
  9696. name = typeof object;
  9697. }
  9698. }
  9699. return name;
  9700. };
  9701. Tools.First = function (array, predicate) {
  9702. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9703. var el = array_1[_i];
  9704. if (predicate(el)) {
  9705. return el;
  9706. }
  9707. }
  9708. return null;
  9709. };
  9710. /**
  9711. * This method will return the name of the full name of the class, including its owning module (if any).
  9712. * 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).
  9713. * @param object the object to get the class name from
  9714. * @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.
  9715. */
  9716. Tools.getFullClassName = function (object, isType) {
  9717. if (isType === void 0) { isType = false; }
  9718. var className = null;
  9719. var moduleName = null;
  9720. if (!isType && object.getClassName) {
  9721. className = object.getClassName();
  9722. }
  9723. else {
  9724. if (object instanceof Object) {
  9725. var classObj = isType ? object : Object.getPrototypeOf(object);
  9726. className = classObj.constructor["__bjsclassName__"];
  9727. moduleName = classObj.constructor["__bjsmoduleName__"];
  9728. }
  9729. if (!className) {
  9730. className = typeof object;
  9731. }
  9732. }
  9733. if (!className) {
  9734. return null;
  9735. }
  9736. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9737. };
  9738. /**
  9739. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9740. * @param array
  9741. */
  9742. Tools.arrayOrStringFeeder = function (array) {
  9743. return function (index) {
  9744. if (index >= array.length) {
  9745. return null;
  9746. }
  9747. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9748. if (val && val.getHashCode) {
  9749. val = val.getHashCode();
  9750. }
  9751. if (typeof val === "string") {
  9752. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9753. }
  9754. return val;
  9755. };
  9756. };
  9757. /**
  9758. * Compute the hashCode of a stream of number
  9759. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9760. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9761. * @return the hash code computed
  9762. */
  9763. Tools.hashCodeFromStream = function (feeder) {
  9764. // Based from here: http://stackoverflow.com/a/7616484/802124
  9765. var hash = 0;
  9766. var index = 0;
  9767. var chr = feeder(index++);
  9768. while (chr != null) {
  9769. hash = ((hash << 5) - hash) + chr;
  9770. hash |= 0; // Convert to 32bit integer
  9771. chr = feeder(index++);
  9772. }
  9773. return hash;
  9774. };
  9775. /**
  9776. * Returns a promise that resolves after the given amount of time.
  9777. * @param delay Number of milliseconds to delay
  9778. * @returns Promise that resolves after the given amount of time
  9779. */
  9780. Tools.DelayAsync = function (delay) {
  9781. return new Promise(function (resolve) {
  9782. setTimeout(function () {
  9783. resolve();
  9784. }, delay);
  9785. });
  9786. };
  9787. Tools.BaseUrl = "";
  9788. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9789. /**
  9790. * Default behaviour for cors in the application.
  9791. * It can be a string if the expected behavior is identical in the entire app.
  9792. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9793. */
  9794. Tools.CorsBehavior = "anonymous";
  9795. Tools.UseFallbackTexture = true;
  9796. /**
  9797. * Use this object to register external classes like custom textures or material
  9798. * to allow the laoders to instantiate them
  9799. */
  9800. Tools.RegisteredExternalClasses = {};
  9801. // Used in case of a texture loading problem
  9802. 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";
  9803. Tools._tmpFloatArray = new Float32Array(1);
  9804. Tools.PreprocessUrl = function (url) {
  9805. return url;
  9806. };
  9807. // Logs
  9808. Tools._NoneLogLevel = 0;
  9809. Tools._MessageLogLevel = 1;
  9810. Tools._WarningLogLevel = 2;
  9811. Tools._ErrorLogLevel = 4;
  9812. Tools._LogCache = "";
  9813. Tools.errorsCount = 0;
  9814. Tools.Log = Tools._LogEnabled;
  9815. Tools.Warn = Tools._WarnEnabled;
  9816. Tools.Error = Tools._ErrorEnabled;
  9817. // Performances
  9818. Tools._PerformanceNoneLogLevel = 0;
  9819. Tools._PerformanceUserMarkLogLevel = 1;
  9820. Tools._PerformanceConsoleLogLevel = 2;
  9821. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9822. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9823. return Tools;
  9824. }());
  9825. BABYLON.Tools = Tools;
  9826. /**
  9827. * This class is used to track a performance counter which is number based.
  9828. * The user has access to many properties which give statistics of different nature
  9829. *
  9830. * The implementer can track two kinds of Performance Counter: time and count
  9831. * 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.
  9832. * 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.
  9833. */
  9834. var PerfCounter = /** @class */ (function () {
  9835. function PerfCounter() {
  9836. this._startMonitoringTime = 0;
  9837. this._min = 0;
  9838. this._max = 0;
  9839. this._average = 0;
  9840. this._lastSecAverage = 0;
  9841. this._current = 0;
  9842. this._totalValueCount = 0;
  9843. this._totalAccumulated = 0;
  9844. this._lastSecAccumulated = 0;
  9845. this._lastSecTime = 0;
  9846. this._lastSecValueCount = 0;
  9847. }
  9848. Object.defineProperty(PerfCounter.prototype, "min", {
  9849. /**
  9850. * Returns the smallest value ever
  9851. */
  9852. get: function () {
  9853. return this._min;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(PerfCounter.prototype, "max", {
  9859. /**
  9860. * Returns the biggest value ever
  9861. */
  9862. get: function () {
  9863. return this._max;
  9864. },
  9865. enumerable: true,
  9866. configurable: true
  9867. });
  9868. Object.defineProperty(PerfCounter.prototype, "average", {
  9869. /**
  9870. * Returns the average value since the performance counter is running
  9871. */
  9872. get: function () {
  9873. return this._average;
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9879. /**
  9880. * Returns the average value of the last second the counter was monitored
  9881. */
  9882. get: function () {
  9883. return this._lastSecAverage;
  9884. },
  9885. enumerable: true,
  9886. configurable: true
  9887. });
  9888. Object.defineProperty(PerfCounter.prototype, "current", {
  9889. /**
  9890. * Returns the current value
  9891. */
  9892. get: function () {
  9893. return this._current;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(PerfCounter.prototype, "total", {
  9899. get: function () {
  9900. return this._totalAccumulated;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(PerfCounter.prototype, "count", {
  9906. get: function () {
  9907. return this._totalValueCount;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. /**
  9913. * Call this method to start monitoring a new frame.
  9914. * 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.
  9915. */
  9916. PerfCounter.prototype.fetchNewFrame = function () {
  9917. this._totalValueCount++;
  9918. this._current = 0;
  9919. this._lastSecValueCount++;
  9920. };
  9921. /**
  9922. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9923. * @param newCount the count value to add to the monitored count
  9924. * @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.
  9925. */
  9926. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9927. if (!PerfCounter.Enabled) {
  9928. return;
  9929. }
  9930. this._current += newCount;
  9931. if (fetchResult) {
  9932. this._fetchResult();
  9933. }
  9934. };
  9935. /**
  9936. * Start monitoring this performance counter
  9937. */
  9938. PerfCounter.prototype.beginMonitoring = function () {
  9939. if (!PerfCounter.Enabled) {
  9940. return;
  9941. }
  9942. this._startMonitoringTime = Tools.Now;
  9943. };
  9944. /**
  9945. * Compute the time lapsed since the previous beginMonitoring() call.
  9946. * @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
  9947. */
  9948. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9949. if (newFrame === void 0) { newFrame = true; }
  9950. if (!PerfCounter.Enabled) {
  9951. return;
  9952. }
  9953. if (newFrame) {
  9954. this.fetchNewFrame();
  9955. }
  9956. var currentTime = Tools.Now;
  9957. this._current = currentTime - this._startMonitoringTime;
  9958. if (newFrame) {
  9959. this._fetchResult();
  9960. }
  9961. };
  9962. PerfCounter.prototype._fetchResult = function () {
  9963. this._totalAccumulated += this._current;
  9964. this._lastSecAccumulated += this._current;
  9965. // Min/Max update
  9966. this._min = Math.min(this._min, this._current);
  9967. this._max = Math.max(this._max, this._current);
  9968. this._average = this._totalAccumulated / this._totalValueCount;
  9969. // Reset last sec?
  9970. var now = Tools.Now;
  9971. if ((now - this._lastSecTime) > 1000) {
  9972. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9973. this._lastSecTime = now;
  9974. this._lastSecAccumulated = 0;
  9975. this._lastSecValueCount = 0;
  9976. }
  9977. };
  9978. PerfCounter.Enabled = true;
  9979. return PerfCounter;
  9980. }());
  9981. BABYLON.PerfCounter = PerfCounter;
  9982. /**
  9983. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9984. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9985. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9986. * @param name The name of the class, case should be preserved
  9987. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9988. */
  9989. function className(name, module) {
  9990. return function (target) {
  9991. target["__bjsclassName__"] = name;
  9992. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9993. };
  9994. }
  9995. BABYLON.className = className;
  9996. /**
  9997. * An implementation of a loop for asynchronous functions.
  9998. */
  9999. var AsyncLoop = /** @class */ (function () {
  10000. /**
  10001. * Constroctor.
  10002. * @param iterations the number of iterations.
  10003. * @param _fn the function to run each iteration
  10004. * @param _successCallback the callback that will be called upon succesful execution
  10005. * @param offset starting offset.
  10006. */
  10007. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10008. if (offset === void 0) { offset = 0; }
  10009. this.iterations = iterations;
  10010. this._fn = _fn;
  10011. this._successCallback = _successCallback;
  10012. this.index = offset - 1;
  10013. this._done = false;
  10014. }
  10015. /**
  10016. * Execute the next iteration. Must be called after the last iteration was finished.
  10017. */
  10018. AsyncLoop.prototype.executeNext = function () {
  10019. if (!this._done) {
  10020. if (this.index + 1 < this.iterations) {
  10021. ++this.index;
  10022. this._fn(this);
  10023. }
  10024. else {
  10025. this.breakLoop();
  10026. }
  10027. }
  10028. };
  10029. /**
  10030. * Break the loop and run the success callback.
  10031. */
  10032. AsyncLoop.prototype.breakLoop = function () {
  10033. this._done = true;
  10034. this._successCallback();
  10035. };
  10036. /**
  10037. * Helper function
  10038. */
  10039. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10040. if (offset === void 0) { offset = 0; }
  10041. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10042. loop.executeNext();
  10043. return loop;
  10044. };
  10045. /**
  10046. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10047. * @param iterations total number of iterations
  10048. * @param syncedIterations number of synchronous iterations in each async iteration.
  10049. * @param fn the function to call each iteration.
  10050. * @param callback a success call back that will be called when iterating stops.
  10051. * @param breakFunction a break condition (optional)
  10052. * @param timeout timeout settings for the setTimeout function. default - 0.
  10053. * @constructor
  10054. */
  10055. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10056. if (timeout === void 0) { timeout = 0; }
  10057. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10058. if (breakFunction && breakFunction())
  10059. loop.breakLoop();
  10060. else {
  10061. setTimeout(function () {
  10062. for (var i = 0; i < syncedIterations; ++i) {
  10063. var iteration = (loop.index * syncedIterations) + i;
  10064. if (iteration >= iterations)
  10065. break;
  10066. fn(iteration);
  10067. if (breakFunction && breakFunction()) {
  10068. loop.breakLoop();
  10069. break;
  10070. }
  10071. }
  10072. loop.executeNext();
  10073. }, timeout);
  10074. }
  10075. }, callback);
  10076. };
  10077. return AsyncLoop;
  10078. }());
  10079. BABYLON.AsyncLoop = AsyncLoop;
  10080. })(BABYLON || (BABYLON = {}));
  10081. //# sourceMappingURL=babylon.tools.js.map
  10082. var BABYLON;
  10083. (function (BABYLON) {
  10084. var PromiseStates;
  10085. (function (PromiseStates) {
  10086. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10087. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10088. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10089. })(PromiseStates || (PromiseStates = {}));
  10090. var FulFillmentAgregator = /** @class */ (function () {
  10091. function FulFillmentAgregator() {
  10092. this.count = 0;
  10093. this.target = 0;
  10094. this.results = [];
  10095. }
  10096. return FulFillmentAgregator;
  10097. }());
  10098. var InternalPromise = /** @class */ (function () {
  10099. function InternalPromise(resolver) {
  10100. var _this = this;
  10101. this._state = PromiseStates.Pending;
  10102. this._children = new Array();
  10103. this._rejectWasConsumed = false;
  10104. if (!resolver) {
  10105. return;
  10106. }
  10107. try {
  10108. resolver(function (value) {
  10109. _this._resolve(value);
  10110. }, function (reason) {
  10111. _this._reject(reason);
  10112. });
  10113. }
  10114. catch (e) {
  10115. this._reject(e);
  10116. }
  10117. }
  10118. Object.defineProperty(InternalPromise.prototype, "_result", {
  10119. get: function () {
  10120. return this._resultValue;
  10121. },
  10122. set: function (value) {
  10123. this._resultValue = value;
  10124. if (this._parent && this._parent._result === undefined) {
  10125. this._parent._result = value;
  10126. }
  10127. },
  10128. enumerable: true,
  10129. configurable: true
  10130. });
  10131. InternalPromise.prototype.catch = function (onRejected) {
  10132. return this.then(undefined, onRejected);
  10133. };
  10134. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10135. var _this = this;
  10136. var newPromise = new InternalPromise();
  10137. newPromise._onFulfilled = onFulfilled;
  10138. newPromise._onRejected = onRejected;
  10139. // Composition
  10140. this._children.push(newPromise);
  10141. newPromise._parent = this;
  10142. if (this._state !== PromiseStates.Pending) {
  10143. BABYLON.Tools.SetImmediate(function () {
  10144. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10145. var returnedValue = newPromise._resolve(_this._result);
  10146. if (returnedValue !== undefined && returnedValue !== null) {
  10147. if (returnedValue._state !== undefined) {
  10148. var returnedPromise = returnedValue;
  10149. newPromise._children.push(returnedPromise);
  10150. returnedPromise._parent = newPromise;
  10151. newPromise = returnedPromise;
  10152. }
  10153. else {
  10154. newPromise._result = returnedValue;
  10155. }
  10156. }
  10157. }
  10158. else {
  10159. newPromise._reject(_this._reason);
  10160. }
  10161. });
  10162. }
  10163. return newPromise;
  10164. };
  10165. InternalPromise.prototype._moveChildren = function (children) {
  10166. var _this = this;
  10167. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10168. this._children.forEach(function (child) {
  10169. child._parent = _this;
  10170. });
  10171. if (this._state === PromiseStates.Fulfilled) {
  10172. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10173. var child = _b[_i];
  10174. child._resolve(this._result);
  10175. }
  10176. }
  10177. else if (this._state === PromiseStates.Rejected) {
  10178. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10179. var child = _d[_c];
  10180. child._reject(this._reason);
  10181. }
  10182. }
  10183. var _a;
  10184. };
  10185. InternalPromise.prototype._resolve = function (value) {
  10186. try {
  10187. this._state = PromiseStates.Fulfilled;
  10188. var returnedValue = null;
  10189. if (this._onFulfilled) {
  10190. returnedValue = this._onFulfilled(value);
  10191. }
  10192. if (returnedValue !== undefined && returnedValue !== null) {
  10193. if (returnedValue._state !== undefined) {
  10194. // Transmit children
  10195. var returnedPromise = returnedValue;
  10196. returnedPromise._parent = this;
  10197. returnedPromise._moveChildren(this._children);
  10198. value = returnedPromise._result;
  10199. }
  10200. else {
  10201. value = returnedValue;
  10202. }
  10203. }
  10204. this._result = value;
  10205. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10206. var child = _a[_i];
  10207. child._resolve(value);
  10208. }
  10209. this._children.length = 0;
  10210. delete this._onFulfilled;
  10211. delete this._onRejected;
  10212. }
  10213. catch (e) {
  10214. this._reject(e, true);
  10215. }
  10216. };
  10217. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10218. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10219. this._state = PromiseStates.Rejected;
  10220. this._reason = reason;
  10221. if (this._onRejected && !onLocalThrow) {
  10222. try {
  10223. this._onRejected(reason);
  10224. this._rejectWasConsumed = true;
  10225. }
  10226. catch (e) {
  10227. reason = e;
  10228. }
  10229. }
  10230. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10231. var child = _a[_i];
  10232. if (this._rejectWasConsumed) {
  10233. child._resolve(null);
  10234. }
  10235. else {
  10236. child._reject(reason);
  10237. }
  10238. }
  10239. this._children.length = 0;
  10240. delete this._onFulfilled;
  10241. delete this._onRejected;
  10242. };
  10243. InternalPromise.resolve = function (value) {
  10244. var newPromise = new InternalPromise();
  10245. newPromise._resolve(value);
  10246. return newPromise;
  10247. };
  10248. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10249. promise.then(function (value) {
  10250. agregator.results[index] = value;
  10251. agregator.count++;
  10252. if (agregator.count === agregator.target) {
  10253. agregator.rootPromise._resolve(agregator.results);
  10254. }
  10255. return null;
  10256. }, function (reason) {
  10257. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10258. agregator.rootPromise._reject(reason);
  10259. }
  10260. });
  10261. };
  10262. InternalPromise.all = function (promises) {
  10263. var newPromise = new InternalPromise();
  10264. var agregator = new FulFillmentAgregator();
  10265. agregator.target = promises.length;
  10266. agregator.rootPromise = newPromise;
  10267. if (promises.length) {
  10268. for (var index = 0; index < promises.length; index++) {
  10269. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10270. }
  10271. }
  10272. else {
  10273. newPromise._resolve([]);
  10274. }
  10275. return newPromise;
  10276. };
  10277. InternalPromise.race = function (promises) {
  10278. var newPromise = new InternalPromise();
  10279. if (promises.length) {
  10280. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10281. var promise = promises_1[_i];
  10282. promise.then(function (value) {
  10283. if (newPromise) {
  10284. newPromise._resolve(value);
  10285. newPromise = null;
  10286. }
  10287. return null;
  10288. }, function (reason) {
  10289. if (newPromise) {
  10290. newPromise._reject(reason);
  10291. newPromise = null;
  10292. }
  10293. });
  10294. }
  10295. }
  10296. return newPromise;
  10297. };
  10298. return InternalPromise;
  10299. }());
  10300. /**
  10301. * Helper class that provides a small promise polyfill
  10302. */
  10303. var PromisePolyfill = /** @class */ (function () {
  10304. function PromisePolyfill() {
  10305. }
  10306. /**
  10307. * Static function used to check if the polyfill is required
  10308. * If this is the case then the function will inject the polyfill to window.Promise
  10309. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10310. */
  10311. PromisePolyfill.Apply = function (force) {
  10312. if (force === void 0) { force = false; }
  10313. if (force || typeof Promise === 'undefined') {
  10314. var root = window;
  10315. root.Promise = InternalPromise;
  10316. }
  10317. };
  10318. return PromisePolyfill;
  10319. }());
  10320. BABYLON.PromisePolyfill = PromisePolyfill;
  10321. })(BABYLON || (BABYLON = {}));
  10322. //# sourceMappingURL=babylon.promise.js.map
  10323. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10324. var BABYLON;
  10325. (function (BABYLON) {
  10326. /**
  10327. * Helper class to push actions to a pool of workers.
  10328. */
  10329. var WorkerPool = /** @class */ (function () {
  10330. /**
  10331. * Constructor
  10332. * @param workers Array of workers to use for actions
  10333. */
  10334. function WorkerPool(workers) {
  10335. this._pendingActions = new Array();
  10336. this._workerInfos = workers.map(function (worker) { return ({
  10337. worker: worker,
  10338. active: false
  10339. }); });
  10340. }
  10341. /**
  10342. * Terminates all workers and clears any pending actions.
  10343. */
  10344. WorkerPool.prototype.dispose = function () {
  10345. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10346. var workerInfo = _a[_i];
  10347. workerInfo.worker.terminate();
  10348. }
  10349. delete this._workerInfos;
  10350. delete this._pendingActions;
  10351. };
  10352. /**
  10353. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10354. * pended until a worker has completed its action.
  10355. * @param action The action to perform. Call onComplete when the action is complete.
  10356. */
  10357. WorkerPool.prototype.push = function (action) {
  10358. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10359. var workerInfo = _a[_i];
  10360. if (!workerInfo.active) {
  10361. this._execute(workerInfo, action);
  10362. return;
  10363. }
  10364. }
  10365. this._pendingActions.push(action);
  10366. };
  10367. WorkerPool.prototype._execute = function (workerInfo, action) {
  10368. var _this = this;
  10369. workerInfo.active = true;
  10370. action(workerInfo.worker, function () {
  10371. workerInfo.active = false;
  10372. var nextAction = _this._pendingActions.shift();
  10373. if (nextAction) {
  10374. _this._execute(workerInfo, nextAction);
  10375. }
  10376. });
  10377. };
  10378. return WorkerPool;
  10379. }());
  10380. BABYLON.WorkerPool = WorkerPool;
  10381. })(BABYLON || (BABYLON = {}));
  10382. //# sourceMappingURL=babylon.workerPool.js.map
  10383. var BABYLON;
  10384. (function (BABYLON) {
  10385. /**
  10386. * @hidden
  10387. **/
  10388. var _AlphaState = /** @class */ (function () {
  10389. /**
  10390. * Initializes the state.
  10391. */
  10392. function _AlphaState() {
  10393. this._isAlphaBlendDirty = false;
  10394. this._isBlendFunctionParametersDirty = false;
  10395. this._isBlendEquationParametersDirty = false;
  10396. this._isBlendConstantsDirty = false;
  10397. this._alphaBlend = false;
  10398. this._blendFunctionParameters = new Array(4);
  10399. this._blendEquationParameters = new Array(2);
  10400. this._blendConstants = new Array(4);
  10401. this.reset();
  10402. }
  10403. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10404. get: function () {
  10405. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10411. get: function () {
  10412. return this._alphaBlend;
  10413. },
  10414. set: function (value) {
  10415. if (this._alphaBlend === value) {
  10416. return;
  10417. }
  10418. this._alphaBlend = value;
  10419. this._isAlphaBlendDirty = true;
  10420. },
  10421. enumerable: true,
  10422. configurable: true
  10423. });
  10424. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10425. if (this._blendConstants[0] === r &&
  10426. this._blendConstants[1] === g &&
  10427. this._blendConstants[2] === b &&
  10428. this._blendConstants[3] === a) {
  10429. return;
  10430. }
  10431. this._blendConstants[0] = r;
  10432. this._blendConstants[1] = g;
  10433. this._blendConstants[2] = b;
  10434. this._blendConstants[3] = a;
  10435. this._isBlendConstantsDirty = true;
  10436. };
  10437. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10438. if (this._blendFunctionParameters[0] === value0 &&
  10439. this._blendFunctionParameters[1] === value1 &&
  10440. this._blendFunctionParameters[2] === value2 &&
  10441. this._blendFunctionParameters[3] === value3) {
  10442. return;
  10443. }
  10444. this._blendFunctionParameters[0] = value0;
  10445. this._blendFunctionParameters[1] = value1;
  10446. this._blendFunctionParameters[2] = value2;
  10447. this._blendFunctionParameters[3] = value3;
  10448. this._isBlendFunctionParametersDirty = true;
  10449. };
  10450. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10451. if (this._blendEquationParameters[0] === rgb &&
  10452. this._blendEquationParameters[1] === alpha) {
  10453. return;
  10454. }
  10455. this._blendEquationParameters[0] = rgb;
  10456. this._blendEquationParameters[1] = alpha;
  10457. this._isBlendEquationParametersDirty = true;
  10458. };
  10459. _AlphaState.prototype.reset = function () {
  10460. this._alphaBlend = false;
  10461. this._blendFunctionParameters[0] = null;
  10462. this._blendFunctionParameters[1] = null;
  10463. this._blendFunctionParameters[2] = null;
  10464. this._blendFunctionParameters[3] = null;
  10465. this._blendEquationParameters[0] = null;
  10466. this._blendEquationParameters[1] = null;
  10467. this._blendConstants[0] = null;
  10468. this._blendConstants[1] = null;
  10469. this._blendConstants[2] = null;
  10470. this._blendConstants[3] = null;
  10471. this._isAlphaBlendDirty = true;
  10472. this._isBlendFunctionParametersDirty = false;
  10473. this._isBlendEquationParametersDirty = false;
  10474. this._isBlendConstantsDirty = false;
  10475. };
  10476. _AlphaState.prototype.apply = function (gl) {
  10477. if (!this.isDirty) {
  10478. return;
  10479. }
  10480. // Alpha blend
  10481. if (this._isAlphaBlendDirty) {
  10482. if (this._alphaBlend) {
  10483. gl.enable(gl.BLEND);
  10484. }
  10485. else {
  10486. gl.disable(gl.BLEND);
  10487. }
  10488. this._isAlphaBlendDirty = false;
  10489. }
  10490. // Alpha function
  10491. if (this._isBlendFunctionParametersDirty) {
  10492. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10493. this._isBlendFunctionParametersDirty = false;
  10494. }
  10495. // Alpha equation
  10496. if (this._isBlendEquationParametersDirty) {
  10497. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10498. this._isBlendEquationParametersDirty = false;
  10499. }
  10500. // Constants
  10501. if (this._isBlendConstantsDirty) {
  10502. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10503. this._isBlendConstantsDirty = false;
  10504. }
  10505. };
  10506. return _AlphaState;
  10507. }());
  10508. BABYLON._AlphaState = _AlphaState;
  10509. })(BABYLON || (BABYLON = {}));
  10510. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10511. var BABYLON;
  10512. (function (BABYLON) {
  10513. /**
  10514. * @hidden
  10515. **/
  10516. var _DepthCullingState = /** @class */ (function () {
  10517. /**
  10518. * Initializes the state.
  10519. */
  10520. function _DepthCullingState() {
  10521. this._isDepthTestDirty = false;
  10522. this._isDepthMaskDirty = false;
  10523. this._isDepthFuncDirty = false;
  10524. this._isCullFaceDirty = false;
  10525. this._isCullDirty = false;
  10526. this._isZOffsetDirty = false;
  10527. this._isFrontFaceDirty = false;
  10528. this.reset();
  10529. }
  10530. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10531. get: function () {
  10532. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10538. get: function () {
  10539. return this._zOffset;
  10540. },
  10541. set: function (value) {
  10542. if (this._zOffset === value) {
  10543. return;
  10544. }
  10545. this._zOffset = value;
  10546. this._isZOffsetDirty = true;
  10547. },
  10548. enumerable: true,
  10549. configurable: true
  10550. });
  10551. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10552. get: function () {
  10553. return this._cullFace;
  10554. },
  10555. set: function (value) {
  10556. if (this._cullFace === value) {
  10557. return;
  10558. }
  10559. this._cullFace = value;
  10560. this._isCullFaceDirty = true;
  10561. },
  10562. enumerable: true,
  10563. configurable: true
  10564. });
  10565. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10566. get: function () {
  10567. return this._cull;
  10568. },
  10569. set: function (value) {
  10570. if (this._cull === value) {
  10571. return;
  10572. }
  10573. this._cull = value;
  10574. this._isCullDirty = true;
  10575. },
  10576. enumerable: true,
  10577. configurable: true
  10578. });
  10579. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10580. get: function () {
  10581. return this._depthFunc;
  10582. },
  10583. set: function (value) {
  10584. if (this._depthFunc === value) {
  10585. return;
  10586. }
  10587. this._depthFunc = value;
  10588. this._isDepthFuncDirty = true;
  10589. },
  10590. enumerable: true,
  10591. configurable: true
  10592. });
  10593. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10594. get: function () {
  10595. return this._depthMask;
  10596. },
  10597. set: function (value) {
  10598. if (this._depthMask === value) {
  10599. return;
  10600. }
  10601. this._depthMask = value;
  10602. this._isDepthMaskDirty = true;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10608. get: function () {
  10609. return this._depthTest;
  10610. },
  10611. set: function (value) {
  10612. if (this._depthTest === value) {
  10613. return;
  10614. }
  10615. this._depthTest = value;
  10616. this._isDepthTestDirty = true;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10622. get: function () {
  10623. return this._frontFace;
  10624. },
  10625. set: function (value) {
  10626. if (this._frontFace === value) {
  10627. return;
  10628. }
  10629. this._frontFace = value;
  10630. this._isFrontFaceDirty = true;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. _DepthCullingState.prototype.reset = function () {
  10636. this._depthMask = true;
  10637. this._depthTest = true;
  10638. this._depthFunc = null;
  10639. this._cullFace = null;
  10640. this._cull = null;
  10641. this._zOffset = 0;
  10642. this._frontFace = null;
  10643. this._isDepthTestDirty = true;
  10644. this._isDepthMaskDirty = true;
  10645. this._isDepthFuncDirty = false;
  10646. this._isCullFaceDirty = false;
  10647. this._isCullDirty = false;
  10648. this._isZOffsetDirty = false;
  10649. this._isFrontFaceDirty = false;
  10650. };
  10651. _DepthCullingState.prototype.apply = function (gl) {
  10652. if (!this.isDirty) {
  10653. return;
  10654. }
  10655. // Cull
  10656. if (this._isCullDirty) {
  10657. if (this.cull) {
  10658. gl.enable(gl.CULL_FACE);
  10659. }
  10660. else {
  10661. gl.disable(gl.CULL_FACE);
  10662. }
  10663. this._isCullDirty = false;
  10664. }
  10665. // Cull face
  10666. if (this._isCullFaceDirty) {
  10667. gl.cullFace(this.cullFace);
  10668. this._isCullFaceDirty = false;
  10669. }
  10670. // Depth mask
  10671. if (this._isDepthMaskDirty) {
  10672. gl.depthMask(this.depthMask);
  10673. this._isDepthMaskDirty = false;
  10674. }
  10675. // Depth test
  10676. if (this._isDepthTestDirty) {
  10677. if (this.depthTest) {
  10678. gl.enable(gl.DEPTH_TEST);
  10679. }
  10680. else {
  10681. gl.disable(gl.DEPTH_TEST);
  10682. }
  10683. this._isDepthTestDirty = false;
  10684. }
  10685. // Depth func
  10686. if (this._isDepthFuncDirty) {
  10687. gl.depthFunc(this.depthFunc);
  10688. this._isDepthFuncDirty = false;
  10689. }
  10690. // zOffset
  10691. if (this._isZOffsetDirty) {
  10692. if (this.zOffset) {
  10693. gl.enable(gl.POLYGON_OFFSET_FILL);
  10694. gl.polygonOffset(this.zOffset, 0);
  10695. }
  10696. else {
  10697. gl.disable(gl.POLYGON_OFFSET_FILL);
  10698. }
  10699. this._isZOffsetDirty = false;
  10700. }
  10701. // Front face
  10702. if (this._isFrontFaceDirty) {
  10703. gl.frontFace(this.frontFace);
  10704. this._isFrontFaceDirty = false;
  10705. }
  10706. };
  10707. return _DepthCullingState;
  10708. }());
  10709. BABYLON._DepthCullingState = _DepthCullingState;
  10710. })(BABYLON || (BABYLON = {}));
  10711. //# sourceMappingURL=babylon.depthCullingState.js.map
  10712. var BABYLON;
  10713. (function (BABYLON) {
  10714. /**
  10715. * @hidden
  10716. **/
  10717. var _StencilState = /** @class */ (function () {
  10718. function _StencilState() {
  10719. this._isStencilTestDirty = false;
  10720. this._isStencilMaskDirty = false;
  10721. this._isStencilFuncDirty = false;
  10722. this._isStencilOpDirty = false;
  10723. this.reset();
  10724. }
  10725. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10726. get: function () {
  10727. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10733. get: function () {
  10734. return this._stencilFunc;
  10735. },
  10736. set: function (value) {
  10737. if (this._stencilFunc === value) {
  10738. return;
  10739. }
  10740. this._stencilFunc = value;
  10741. this._isStencilFuncDirty = true;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10747. get: function () {
  10748. return this._stencilFuncRef;
  10749. },
  10750. set: function (value) {
  10751. if (this._stencilFuncRef === value) {
  10752. return;
  10753. }
  10754. this._stencilFuncRef = value;
  10755. this._isStencilFuncDirty = true;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10761. get: function () {
  10762. return this._stencilFuncMask;
  10763. },
  10764. set: function (value) {
  10765. if (this._stencilFuncMask === value) {
  10766. return;
  10767. }
  10768. this._stencilFuncMask = value;
  10769. this._isStencilFuncDirty = true;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10775. get: function () {
  10776. return this._stencilOpStencilFail;
  10777. },
  10778. set: function (value) {
  10779. if (this._stencilOpStencilFail === value) {
  10780. return;
  10781. }
  10782. this._stencilOpStencilFail = value;
  10783. this._isStencilOpDirty = true;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10789. get: function () {
  10790. return this._stencilOpDepthFail;
  10791. },
  10792. set: function (value) {
  10793. if (this._stencilOpDepthFail === value) {
  10794. return;
  10795. }
  10796. this._stencilOpDepthFail = value;
  10797. this._isStencilOpDirty = true;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10803. get: function () {
  10804. return this._stencilOpStencilDepthPass;
  10805. },
  10806. set: function (value) {
  10807. if (this._stencilOpStencilDepthPass === value) {
  10808. return;
  10809. }
  10810. this._stencilOpStencilDepthPass = value;
  10811. this._isStencilOpDirty = true;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10817. get: function () {
  10818. return this._stencilMask;
  10819. },
  10820. set: function (value) {
  10821. if (this._stencilMask === value) {
  10822. return;
  10823. }
  10824. this._stencilMask = value;
  10825. this._isStencilMaskDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10831. get: function () {
  10832. return this._stencilTest;
  10833. },
  10834. set: function (value) {
  10835. if (this._stencilTest === value) {
  10836. return;
  10837. }
  10838. this._stencilTest = value;
  10839. this._isStencilTestDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. _StencilState.prototype.reset = function () {
  10845. this._stencilTest = false;
  10846. this._stencilMask = 0xFF;
  10847. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10848. this._stencilFuncRef = 1;
  10849. this._stencilFuncMask = 0xFF;
  10850. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10851. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10852. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10853. this._isStencilTestDirty = true;
  10854. this._isStencilMaskDirty = true;
  10855. this._isStencilFuncDirty = true;
  10856. this._isStencilOpDirty = true;
  10857. };
  10858. _StencilState.prototype.apply = function (gl) {
  10859. if (!this.isDirty) {
  10860. return;
  10861. }
  10862. // Stencil test
  10863. if (this._isStencilTestDirty) {
  10864. if (this.stencilTest) {
  10865. gl.enable(gl.STENCIL_TEST);
  10866. }
  10867. else {
  10868. gl.disable(gl.STENCIL_TEST);
  10869. }
  10870. this._isStencilTestDirty = false;
  10871. }
  10872. // Stencil mask
  10873. if (this._isStencilMaskDirty) {
  10874. gl.stencilMask(this.stencilMask);
  10875. this._isStencilMaskDirty = false;
  10876. }
  10877. // Stencil func
  10878. if (this._isStencilFuncDirty) {
  10879. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10880. this._isStencilFuncDirty = false;
  10881. }
  10882. // Stencil op
  10883. if (this._isStencilOpDirty) {
  10884. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10885. this._isStencilOpDirty = false;
  10886. }
  10887. };
  10888. return _StencilState;
  10889. }());
  10890. BABYLON._StencilState = _StencilState;
  10891. })(BABYLON || (BABYLON = {}));
  10892. //# sourceMappingURL=babylon.stencilState.js.map
  10893. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10894. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10895. s = arguments[i];
  10896. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10897. t[p] = s[p];
  10898. }
  10899. return t;
  10900. };
  10901. var BABYLON;
  10902. (function (BABYLON) {
  10903. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10904. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10905. };
  10906. var compileRawShader = function (gl, source, type) {
  10907. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10908. gl.shaderSource(shader, source);
  10909. gl.compileShader(shader);
  10910. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10911. var log = gl.getShaderInfoLog(shader);
  10912. if (log) {
  10913. throw new Error(log);
  10914. }
  10915. }
  10916. if (!shader) {
  10917. throw new Error("Something went wrong while compile the shader.");
  10918. }
  10919. return shader;
  10920. };
  10921. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10922. var magFilter = gl.NEAREST;
  10923. var minFilter = gl.NEAREST;
  10924. switch (samplingMode) {
  10925. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10926. magFilter = gl.LINEAR;
  10927. if (generateMipMaps) {
  10928. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10929. }
  10930. else {
  10931. minFilter = gl.LINEAR;
  10932. }
  10933. break;
  10934. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10935. magFilter = gl.LINEAR;
  10936. if (generateMipMaps) {
  10937. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10938. }
  10939. else {
  10940. minFilter = gl.LINEAR;
  10941. }
  10942. break;
  10943. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10944. magFilter = gl.NEAREST;
  10945. if (generateMipMaps) {
  10946. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10947. }
  10948. else {
  10949. minFilter = gl.NEAREST;
  10950. }
  10951. break;
  10952. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10953. magFilter = gl.NEAREST;
  10954. if (generateMipMaps) {
  10955. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10956. }
  10957. else {
  10958. minFilter = gl.NEAREST;
  10959. }
  10960. break;
  10961. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10962. magFilter = gl.NEAREST;
  10963. if (generateMipMaps) {
  10964. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10965. }
  10966. else {
  10967. minFilter = gl.LINEAR;
  10968. }
  10969. break;
  10970. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10971. magFilter = gl.NEAREST;
  10972. if (generateMipMaps) {
  10973. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10974. }
  10975. else {
  10976. minFilter = gl.LINEAR;
  10977. }
  10978. break;
  10979. case BABYLON.Texture.NEAREST_LINEAR:
  10980. magFilter = gl.NEAREST;
  10981. minFilter = gl.LINEAR;
  10982. break;
  10983. case BABYLON.Texture.NEAREST_NEAREST:
  10984. magFilter = gl.NEAREST;
  10985. minFilter = gl.NEAREST;
  10986. break;
  10987. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10988. magFilter = gl.LINEAR;
  10989. if (generateMipMaps) {
  10990. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10991. }
  10992. else {
  10993. minFilter = gl.NEAREST;
  10994. }
  10995. break;
  10996. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10997. magFilter = gl.LINEAR;
  10998. if (generateMipMaps) {
  10999. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11000. }
  11001. else {
  11002. minFilter = gl.NEAREST;
  11003. }
  11004. break;
  11005. case BABYLON.Texture.LINEAR_LINEAR:
  11006. magFilter = gl.LINEAR;
  11007. minFilter = gl.LINEAR;
  11008. break;
  11009. case BABYLON.Texture.LINEAR_NEAREST:
  11010. magFilter = gl.LINEAR;
  11011. minFilter = gl.NEAREST;
  11012. break;
  11013. }
  11014. return {
  11015. min: minFilter,
  11016. mag: magFilter
  11017. };
  11018. };
  11019. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11020. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11021. var img;
  11022. var onload = function () {
  11023. loadedImages[index] = img;
  11024. loadedImages._internalCount++;
  11025. if (scene) {
  11026. scene._removePendingData(img);
  11027. }
  11028. if (loadedImages._internalCount === 6) {
  11029. onfinish(loadedImages);
  11030. }
  11031. };
  11032. var onerror = function (message, exception) {
  11033. if (scene) {
  11034. scene._removePendingData(img);
  11035. }
  11036. if (onErrorCallBack) {
  11037. onErrorCallBack(message, exception);
  11038. }
  11039. };
  11040. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11041. if (scene) {
  11042. scene._addPendingData(img);
  11043. }
  11044. };
  11045. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11046. if (onError === void 0) { onError = null; }
  11047. var loadedImages = [];
  11048. loadedImages._internalCount = 0;
  11049. for (var index = 0; index < 6; index++) {
  11050. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11051. }
  11052. };
  11053. var BufferPointer = /** @class */ (function () {
  11054. function BufferPointer() {
  11055. }
  11056. return BufferPointer;
  11057. }());
  11058. /**
  11059. * Interface for attribute information associated with buffer instanciation
  11060. */
  11061. var InstancingAttributeInfo = /** @class */ (function () {
  11062. function InstancingAttributeInfo() {
  11063. }
  11064. return InstancingAttributeInfo;
  11065. }());
  11066. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11067. /**
  11068. * Define options used to create a render target texture
  11069. */
  11070. var RenderTargetCreationOptions = /** @class */ (function () {
  11071. function RenderTargetCreationOptions() {
  11072. }
  11073. return RenderTargetCreationOptions;
  11074. }());
  11075. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11076. /**
  11077. * Define options used to create a depth texture
  11078. */
  11079. var DepthTextureCreationOptions = /** @class */ (function () {
  11080. function DepthTextureCreationOptions() {
  11081. }
  11082. return DepthTextureCreationOptions;
  11083. }());
  11084. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11085. /**
  11086. * Class used to describe the capabilities of the engine relatively to the current browser
  11087. */
  11088. var EngineCapabilities = /** @class */ (function () {
  11089. function EngineCapabilities() {
  11090. }
  11091. return EngineCapabilities;
  11092. }());
  11093. BABYLON.EngineCapabilities = EngineCapabilities;
  11094. /**
  11095. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11096. */
  11097. var Engine = /** @class */ (function () {
  11098. /**
  11099. * Creates a new engine
  11100. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11101. * @param antialias defines enable antialiasing (default: false)
  11102. * @param options defines further options to be sent to the getContext() function
  11103. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11104. */
  11105. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11106. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11107. var _this = this;
  11108. // Public members
  11109. /**
  11110. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11111. */
  11112. this.forcePOTTextures = false;
  11113. /**
  11114. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11115. */
  11116. this.isFullscreen = false;
  11117. /**
  11118. * Gets a boolean indicating if the pointer is currently locked
  11119. */
  11120. this.isPointerLock = false;
  11121. /**
  11122. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11123. */
  11124. this.cullBackFaces = true;
  11125. /**
  11126. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11127. */
  11128. this.renderEvenInBackground = true;
  11129. /**
  11130. * Gets or sets a boolean indicating that cache can be kept between frames
  11131. */
  11132. this.preventCacheWipeBetweenFrames = false;
  11133. /**
  11134. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11135. **/
  11136. this.enableOfflineSupport = false;
  11137. /**
  11138. * 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)
  11139. **/
  11140. this.disableManifestCheck = false;
  11141. /**
  11142. * Gets the list of created scenes
  11143. */
  11144. this.scenes = new Array();
  11145. /**
  11146. * Gets the list of created postprocesses
  11147. */
  11148. this.postProcesses = new Array();
  11149. // Observables
  11150. /**
  11151. * Observable event triggered each time the rendering canvas is resized
  11152. */
  11153. this.onResizeObservable = new BABYLON.Observable();
  11154. /**
  11155. * Observable event triggered each time the canvas loses focus
  11156. */
  11157. this.onCanvasBlurObservable = new BABYLON.Observable();
  11158. /**
  11159. * Observable event triggered each time the canvas gains focus
  11160. */
  11161. this.onCanvasFocusObservable = new BABYLON.Observable();
  11162. /**
  11163. * Observable event triggered each time the canvas receives pointerout event
  11164. */
  11165. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11166. /**
  11167. * Observable event triggered before each texture is initialized
  11168. */
  11169. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11170. //WebVR
  11171. this._vrDisplay = undefined;
  11172. this._vrSupported = false;
  11173. this._vrExclusivePointerMode = false;
  11174. // Uniform buffers list
  11175. /**
  11176. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11177. */
  11178. this.disableUniformBuffers = false;
  11179. /** @hidden */
  11180. this._uniformBuffers = new Array();
  11181. // Observables
  11182. /**
  11183. * Observable raised when the engine begins a new frame
  11184. */
  11185. this.onBeginFrameObservable = new BABYLON.Observable();
  11186. /**
  11187. * Observable raised when the engine ends the current frame
  11188. */
  11189. this.onEndFrameObservable = new BABYLON.Observable();
  11190. /**
  11191. * Observable raised when the engine is about to compile a shader
  11192. */
  11193. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11194. /**
  11195. * Observable raised when the engine has jsut compiled a shader
  11196. */
  11197. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11198. this._windowIsBackground = false;
  11199. this._webGLVersion = 1.0;
  11200. /** @hidden */
  11201. this._badOS = false;
  11202. /** @hidden */
  11203. this._badDesktopOS = false;
  11204. /**
  11205. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11206. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11207. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11208. */
  11209. this.disableTextureBindingOptimization = false;
  11210. /**
  11211. * Observable signaled when VR display mode changes
  11212. */
  11213. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11214. /**
  11215. * Observable signaled when VR request present is complete
  11216. */
  11217. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11218. /**
  11219. * Observable signaled when VR request present starts
  11220. */
  11221. this.onVRRequestPresentStart = new BABYLON.Observable();
  11222. this._colorWrite = true;
  11223. /** @hidden */
  11224. this._drawCalls = new BABYLON.PerfCounter();
  11225. /** @hidden */
  11226. this._textureCollisions = new BABYLON.PerfCounter();
  11227. this._renderingQueueLaunched = false;
  11228. this._activeRenderLoops = new Array();
  11229. // Deterministic lockstepMaxSteps
  11230. this._deterministicLockstep = false;
  11231. this._lockstepMaxSteps = 4;
  11232. // Lost context
  11233. /**
  11234. * Observable signaled when a context lost event is raised
  11235. */
  11236. this.onContextLostObservable = new BABYLON.Observable();
  11237. /**
  11238. * Observable signaled when a context restored event is raised
  11239. */
  11240. this.onContextRestoredObservable = new BABYLON.Observable();
  11241. this._contextWasLost = false;
  11242. this._doNotHandleContextLost = false;
  11243. // FPS
  11244. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11245. this._fps = 60;
  11246. this._deltaTime = 0;
  11247. /**
  11248. * Turn this value on if you want to pause FPS computation when in background
  11249. */
  11250. this.disablePerformanceMonitorInBackground = false;
  11251. // States
  11252. /** @hidden */
  11253. this._depthCullingState = new BABYLON._DepthCullingState();
  11254. /** @hidden */
  11255. this._stencilState = new BABYLON._StencilState();
  11256. /** @hidden */
  11257. this._alphaState = new BABYLON._AlphaState();
  11258. /** @hidden */
  11259. this._alphaMode = Engine.ALPHA_DISABLE;
  11260. // Cache
  11261. this._internalTexturesCache = new Array();
  11262. /** @hidden */
  11263. this._activeChannel = 0;
  11264. this._currentTextureChannel = -1;
  11265. /** @hidden */
  11266. this._boundTexturesCache = {};
  11267. this._compiledEffects = {};
  11268. this._vertexAttribArraysEnabled = [];
  11269. this._uintIndicesCurrentlySet = false;
  11270. this._currentBoundBuffer = new Array();
  11271. this._currentBufferPointers = new Array();
  11272. this._currentInstanceLocations = new Array();
  11273. this._currentInstanceBuffers = new Array();
  11274. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11275. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11276. this._vaoRecordInProgress = false;
  11277. this._mustWipeVertexAttributes = false;
  11278. this._nextFreeTextureSlots = new Array();
  11279. this._maxSimultaneousTextures = 0;
  11280. this._activeRequests = new Array();
  11281. // Hardware supported Compressed Textures
  11282. this._texturesSupported = new Array();
  11283. this._onVRFullScreenTriggered = function () {
  11284. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11285. //get the old size before we change
  11286. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11287. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11288. //get the width and height, change the render size
  11289. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11290. _this.setHardwareScalingLevel(1);
  11291. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11292. }
  11293. else {
  11294. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11295. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11296. }
  11297. };
  11298. this._boundUniforms = {};
  11299. // Register promises
  11300. BABYLON.PromisePolyfill.Apply();
  11301. var canvas = null;
  11302. Engine.Instances.push(this);
  11303. if (!canvasOrContext) {
  11304. return;
  11305. }
  11306. options = options || {};
  11307. if (canvasOrContext.getContext) {
  11308. canvas = canvasOrContext;
  11309. this._renderingCanvas = canvas;
  11310. if (antialias != null) {
  11311. options.antialias = antialias;
  11312. }
  11313. if (options.deterministicLockstep === undefined) {
  11314. options.deterministicLockstep = false;
  11315. }
  11316. if (options.lockstepMaxSteps === undefined) {
  11317. options.lockstepMaxSteps = 4;
  11318. }
  11319. if (options.preserveDrawingBuffer === undefined) {
  11320. options.preserveDrawingBuffer = false;
  11321. }
  11322. if (options.audioEngine === undefined) {
  11323. options.audioEngine = true;
  11324. }
  11325. if (options.stencil === undefined) {
  11326. options.stencil = true;
  11327. }
  11328. this._deterministicLockstep = options.deterministicLockstep;
  11329. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11330. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11331. // Exceptions
  11332. if (navigator && navigator.userAgent) {
  11333. var ua = navigator.userAgent;
  11334. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11335. var exception = _a[_i];
  11336. var key = exception.key;
  11337. var targets = exception.targets;
  11338. if (ua.indexOf(key) > -1) {
  11339. if (exception.capture && exception.captureConstraint) {
  11340. var capture = exception.capture;
  11341. var constraint = exception.captureConstraint;
  11342. var regex = new RegExp(capture);
  11343. var matches = regex.exec(ua);
  11344. if (matches && matches.length > 0) {
  11345. var capturedValue = parseInt(matches[matches.length - 1]);
  11346. if (capturedValue >= constraint) {
  11347. continue;
  11348. }
  11349. }
  11350. }
  11351. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11352. var target = targets_1[_b];
  11353. switch (target) {
  11354. case "uniformBuffer":
  11355. this.disableUniformBuffers = true;
  11356. break;
  11357. case "textureBindingOptimization":
  11358. this.disableTextureBindingOptimization = true;
  11359. break;
  11360. }
  11361. }
  11362. }
  11363. }
  11364. }
  11365. // GL
  11366. if (!options.disableWebGL2Support) {
  11367. try {
  11368. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11369. if (this._gl) {
  11370. this._webGLVersion = 2.0;
  11371. }
  11372. }
  11373. catch (e) {
  11374. // Do nothing
  11375. }
  11376. }
  11377. if (!this._gl) {
  11378. if (!canvas) {
  11379. throw new Error("The provided canvas is null or undefined.");
  11380. }
  11381. try {
  11382. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11383. }
  11384. catch (e) {
  11385. throw new Error("WebGL not supported");
  11386. }
  11387. }
  11388. if (!this._gl) {
  11389. throw new Error("WebGL not supported");
  11390. }
  11391. this._onCanvasFocus = function () {
  11392. _this.onCanvasFocusObservable.notifyObservers(_this);
  11393. };
  11394. this._onCanvasBlur = function () {
  11395. _this.onCanvasBlurObservable.notifyObservers(_this);
  11396. };
  11397. canvas.addEventListener("focus", this._onCanvasFocus);
  11398. canvas.addEventListener("blur", this._onCanvasBlur);
  11399. this._onBlur = function () {
  11400. if (_this.disablePerformanceMonitorInBackground) {
  11401. _this._performanceMonitor.disable();
  11402. }
  11403. _this._windowIsBackground = true;
  11404. };
  11405. this._onFocus = function () {
  11406. if (_this.disablePerformanceMonitorInBackground) {
  11407. _this._performanceMonitor.enable();
  11408. }
  11409. _this._windowIsBackground = false;
  11410. };
  11411. this._onCanvasPointerOut = function (ev) {
  11412. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11413. };
  11414. window.addEventListener("blur", this._onBlur);
  11415. window.addEventListener("focus", this._onFocus);
  11416. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11417. // Context lost
  11418. if (!this._doNotHandleContextLost) {
  11419. this._onContextLost = function (evt) {
  11420. evt.preventDefault();
  11421. _this._contextWasLost = true;
  11422. BABYLON.Tools.Warn("WebGL context lost.");
  11423. _this.onContextLostObservable.notifyObservers(_this);
  11424. };
  11425. this._onContextRestored = function (evt) {
  11426. // Adding a timeout to avoid race condition at browser level
  11427. setTimeout(function () {
  11428. // Rebuild gl context
  11429. _this._initGLContext();
  11430. // Rebuild effects
  11431. _this._rebuildEffects();
  11432. // Rebuild textures
  11433. _this._rebuildInternalTextures();
  11434. // Rebuild buffers
  11435. _this._rebuildBuffers();
  11436. // Cache
  11437. _this.wipeCaches(true);
  11438. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11439. _this.onContextRestoredObservable.notifyObservers(_this);
  11440. _this._contextWasLost = false;
  11441. }, 0);
  11442. };
  11443. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11444. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11445. }
  11446. }
  11447. else {
  11448. this._gl = canvasOrContext;
  11449. this._renderingCanvas = this._gl.canvas;
  11450. if (this._gl.renderbufferStorageMultisample) {
  11451. this._webGLVersion = 2.0;
  11452. }
  11453. options.stencil = this._gl.getContextAttributes().stencil;
  11454. }
  11455. // Viewport
  11456. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11457. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11458. this.resize();
  11459. this._isStencilEnable = options.stencil ? true : false;
  11460. this._initGLContext();
  11461. if (canvas) {
  11462. // Fullscreen
  11463. this._onFullscreenChange = function () {
  11464. if (document.fullscreen !== undefined) {
  11465. _this.isFullscreen = document.fullscreen;
  11466. }
  11467. else if (document.mozFullScreen !== undefined) {
  11468. _this.isFullscreen = document.mozFullScreen;
  11469. }
  11470. else if (document.webkitIsFullScreen !== undefined) {
  11471. _this.isFullscreen = document.webkitIsFullScreen;
  11472. }
  11473. else if (document.msIsFullScreen !== undefined) {
  11474. _this.isFullscreen = document.msIsFullScreen;
  11475. }
  11476. // Pointer lock
  11477. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11478. canvas.requestPointerLock = canvas.requestPointerLock ||
  11479. canvas.msRequestPointerLock ||
  11480. canvas.mozRequestPointerLock ||
  11481. canvas.webkitRequestPointerLock;
  11482. if (canvas.requestPointerLock) {
  11483. canvas.requestPointerLock();
  11484. }
  11485. }
  11486. };
  11487. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11488. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11489. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11490. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11491. // Pointer lock
  11492. this._onPointerLockChange = function () {
  11493. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11494. document.webkitPointerLockElement === canvas ||
  11495. document.msPointerLockElement === canvas ||
  11496. document.pointerLockElement === canvas);
  11497. };
  11498. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11499. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11500. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11501. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11502. this._onVRDisplayPointerRestricted = function () {
  11503. if (canvas) {
  11504. canvas.requestPointerLock();
  11505. }
  11506. };
  11507. this._onVRDisplayPointerUnrestricted = function () {
  11508. document.exitPointerLock();
  11509. };
  11510. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11511. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11512. }
  11513. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11514. Engine.audioEngine = new BABYLON.AudioEngine();
  11515. }
  11516. // Prepare buffer pointers
  11517. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11518. this._currentBufferPointers[i] = new BufferPointer();
  11519. }
  11520. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11521. // Load WebVR Devices
  11522. if (options.autoEnableWebVR) {
  11523. this.initWebVR();
  11524. }
  11525. // Detect if we are running on a faulty buggy OS.
  11526. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11527. // Detect if we are running on a faulty buggy desktop OS.
  11528. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11529. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11530. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11531. }
  11532. Object.defineProperty(Engine, "LastCreatedEngine", {
  11533. /**
  11534. * Gets the latest created engine
  11535. */
  11536. get: function () {
  11537. if (Engine.Instances.length === 0) {
  11538. return null;
  11539. }
  11540. return Engine.Instances[Engine.Instances.length - 1];
  11541. },
  11542. enumerable: true,
  11543. configurable: true
  11544. });
  11545. Object.defineProperty(Engine, "LastCreatedScene", {
  11546. /**
  11547. * Gets the latest created scene
  11548. */
  11549. get: function () {
  11550. var lastCreatedEngine = Engine.LastCreatedEngine;
  11551. if (!lastCreatedEngine) {
  11552. return null;
  11553. }
  11554. if (lastCreatedEngine.scenes.length === 0) {
  11555. return null;
  11556. }
  11557. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11558. },
  11559. enumerable: true,
  11560. configurable: true
  11561. });
  11562. /**
  11563. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11564. * @param flag defines which part of the materials must be marked as dirty
  11565. * @param predicate defines a predicate used to filter which materials should be affected
  11566. */
  11567. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11568. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11569. var engine = Engine.Instances[engineIndex];
  11570. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11571. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11572. }
  11573. }
  11574. };
  11575. Object.defineProperty(Engine, "NEVER", {
  11576. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11577. get: function () {
  11578. return Engine._NEVER;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(Engine, "ALWAYS", {
  11584. /** 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 */
  11585. get: function () {
  11586. return Engine._ALWAYS;
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Object.defineProperty(Engine, "LESS", {
  11592. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11593. get: function () {
  11594. return Engine._LESS;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. Object.defineProperty(Engine, "EQUAL", {
  11600. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11601. get: function () {
  11602. return Engine._EQUAL;
  11603. },
  11604. enumerable: true,
  11605. configurable: true
  11606. });
  11607. Object.defineProperty(Engine, "LEQUAL", {
  11608. /** 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 */
  11609. get: function () {
  11610. return Engine._LEQUAL;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Engine, "GREATER", {
  11616. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11617. get: function () {
  11618. return Engine._GREATER;
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. Object.defineProperty(Engine, "GEQUAL", {
  11624. /** 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 */
  11625. get: function () {
  11626. return Engine._GEQUAL;
  11627. },
  11628. enumerable: true,
  11629. configurable: true
  11630. });
  11631. Object.defineProperty(Engine, "NOTEQUAL", {
  11632. /** 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 */
  11633. get: function () {
  11634. return Engine._NOTEQUAL;
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. Object.defineProperty(Engine, "KEEP", {
  11640. /** Passed to stencilOperation to specify that stencil value must be kept */
  11641. get: function () {
  11642. return Engine._KEEP;
  11643. },
  11644. enumerable: true,
  11645. configurable: true
  11646. });
  11647. Object.defineProperty(Engine, "REPLACE", {
  11648. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11649. get: function () {
  11650. return Engine._REPLACE;
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Engine, "INCR", {
  11656. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11657. get: function () {
  11658. return Engine._INCR;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(Engine, "DECR", {
  11664. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11665. get: function () {
  11666. return Engine._DECR;
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(Engine, "INVERT", {
  11672. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11673. get: function () {
  11674. return Engine._INVERT;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "INCR_WRAP", {
  11680. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11681. get: function () {
  11682. return Engine._INCR_WRAP;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Engine, "DECR_WRAP", {
  11688. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11689. get: function () {
  11690. return Engine._DECR_WRAP;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11696. // Alpha
  11697. /** Defines that alpha blending is disabled */
  11698. get: function () {
  11699. return Engine._ALPHA_DISABLE;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11705. /** Defines that alpha blending to SRC + DEST */
  11706. get: function () {
  11707. return Engine._ALPHA_ONEONE;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Engine, "ALPHA_ADD", {
  11713. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11714. get: function () {
  11715. return Engine._ALPHA_ADD;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11721. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11722. get: function () {
  11723. return Engine._ALPHA_COMBINE;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11729. /** Defines that alpha blending to DEST - SRC * DEST */
  11730. get: function () {
  11731. return Engine._ALPHA_SUBTRACT;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11737. /** Defines that alpha blending to SRC * DEST */
  11738. get: function () {
  11739. return Engine._ALPHA_MULTIPLY;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11745. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11746. get: function () {
  11747. return Engine._ALPHA_MAXIMIZED;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11753. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11754. get: function () {
  11755. return Engine._ALPHA_PREMULTIPLIED;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11761. /**
  11762. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11763. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11764. */
  11765. get: function () {
  11766. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11772. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11773. get: function () {
  11774. return Engine._ALPHA_INTERPOLATE;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11780. /**
  11781. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11782. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11783. */
  11784. get: function () {
  11785. return Engine._ALPHA_SCREENMODE;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11791. // Delays
  11792. /** Defines that the ressource is not delayed*/
  11793. get: function () {
  11794. return Engine._DELAYLOADSTATE_NONE;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11800. /** Defines that the ressource was successfully delay loaded */
  11801. get: function () {
  11802. return Engine._DELAYLOADSTATE_LOADED;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11808. /** Defines that the ressource is currently delay loading */
  11809. get: function () {
  11810. return Engine._DELAYLOADSTATE_LOADING;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11816. /** Defines that the ressource is delayed and has not started loading */
  11817. get: function () {
  11818. return Engine._DELAYLOADSTATE_NOTLOADED;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11824. /** ALPHA */
  11825. get: function () {
  11826. return Engine._TEXTUREFORMAT_ALPHA;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11832. /** LUMINANCE */
  11833. get: function () {
  11834. return Engine._TEXTUREFORMAT_LUMINANCE;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11840. /**
  11841. * R32F
  11842. */
  11843. get: function () {
  11844. return Engine._TEXTUREFORMAT_R32F;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11850. /**
  11851. * RG32F
  11852. */
  11853. get: function () {
  11854. return Engine._TEXTUREFORMAT_RG32F;
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11860. /**
  11861. * RGB32F
  11862. */
  11863. get: function () {
  11864. return Engine._TEXTUREFORMAT_RGB32F;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11870. /**
  11871. * RGBA32F
  11872. */
  11873. get: function () {
  11874. return Engine._TEXTUREFORMAT_RGBA32F;
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11880. /** LUMINANCE_ALPHA */
  11881. get: function () {
  11882. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11888. /** RGB */
  11889. get: function () {
  11890. return Engine._TEXTUREFORMAT_RGB;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11896. /** RGBA */
  11897. get: function () {
  11898. return Engine._TEXTUREFORMAT_RGBA;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11904. /** UNSIGNED_INT */
  11905. get: function () {
  11906. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11912. /** FLOAT */
  11913. get: function () {
  11914. return Engine._TEXTURETYPE_FLOAT;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11920. /** HALF_FLOAT */
  11921. get: function () {
  11922. return Engine._TEXTURETYPE_HALF_FLOAT;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11928. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11929. get: function () {
  11930. return Engine._SCALEMODE_FLOOR;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11936. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11937. get: function () {
  11938. return Engine._SCALEMODE_NEAREST;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11944. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11945. get: function () {
  11946. return Engine._SCALEMODE_CEILING;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "Version", {
  11952. /**
  11953. * Returns the current version of the framework
  11954. */
  11955. get: function () {
  11956. return "3.2.0-beta.5";
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11962. /**
  11963. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11964. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11965. */
  11966. get: function () {
  11967. return this._vrExclusivePointerMode;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11973. /**
  11974. * Gets a boolean indicating that the engine supports uniform buffers
  11975. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11976. */
  11977. get: function () {
  11978. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11984. /**
  11985. * Gets a boolean indicating that only power of 2 textures are supported
  11986. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11987. */
  11988. get: function () {
  11989. return this._webGLVersion < 2 || this.forcePOTTextures;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11995. /**
  11996. * Gets the performance monitor attached to this engine
  11997. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11998. */
  11999. get: function () {
  12000. return this._performanceMonitor;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12006. /**
  12007. * Gets the list of texture formats supported
  12008. */
  12009. get: function () {
  12010. return this._texturesSupported;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12016. /**
  12017. * Gets the list of texture formats in use
  12018. */
  12019. get: function () {
  12020. return this._textureFormatInUse;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine.prototype, "currentViewport", {
  12026. /**
  12027. * Gets the current viewport
  12028. */
  12029. get: function () {
  12030. return this._cachedViewport;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12036. /**
  12037. * Gets the default empty texture
  12038. */
  12039. get: function () {
  12040. if (!this._emptyTexture) {
  12041. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12042. }
  12043. return this._emptyTexture;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12049. /**
  12050. * Gets the default empty 3D texture
  12051. */
  12052. get: function () {
  12053. if (!this._emptyTexture3D) {
  12054. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12055. }
  12056. return this._emptyTexture3D;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12062. /**
  12063. * Gets the default empty cube texture
  12064. */
  12065. get: function () {
  12066. if (!this._emptyCubeTexture) {
  12067. var faceData = new Uint8Array(4);
  12068. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12069. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12070. }
  12071. return this._emptyCubeTexture;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Engine.prototype._rebuildInternalTextures = function () {
  12077. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12078. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12079. var internalTexture = currentState_1[_i];
  12080. internalTexture._rebuild();
  12081. }
  12082. };
  12083. Engine.prototype._rebuildEffects = function () {
  12084. for (var key in this._compiledEffects) {
  12085. var effect = this._compiledEffects[key];
  12086. effect._prepareEffect();
  12087. }
  12088. BABYLON.Effect.ResetCache();
  12089. };
  12090. Engine.prototype._rebuildBuffers = function () {
  12091. // Index / Vertex
  12092. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12093. var scene = _a[_i];
  12094. scene.resetCachedMaterial();
  12095. scene._rebuildGeometries();
  12096. scene._rebuildTextures();
  12097. }
  12098. // Uniforms
  12099. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12100. var uniformBuffer = _c[_b];
  12101. uniformBuffer._rebuild();
  12102. }
  12103. };
  12104. Engine.prototype._initGLContext = function () {
  12105. // Caps
  12106. this._caps = new EngineCapabilities();
  12107. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12108. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12109. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12110. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12111. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12112. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12113. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12114. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12115. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12116. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12117. // Infos
  12118. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12119. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12120. if (rendererInfo != null) {
  12121. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12122. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12123. }
  12124. if (!this._glVendor) {
  12125. this._glVendor = "Unknown vendor";
  12126. }
  12127. if (!this._glRenderer) {
  12128. this._glRenderer = "Unknown renderer";
  12129. }
  12130. // Constants
  12131. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12132. if (this._gl.RGBA16F !== 0x881A) {
  12133. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12134. }
  12135. if (this._gl.RGBA32F !== 0x8814) {
  12136. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12137. }
  12138. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12139. this._gl.DEPTH24_STENCIL8 = 35056;
  12140. }
  12141. // Extensions
  12142. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12143. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12144. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12145. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12146. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12147. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12148. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12149. 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');
  12150. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12151. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12152. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12153. this._caps.highPrecisionShaderSupported = true;
  12154. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12155. if (this._caps.timerQuery) {
  12156. if (this._webGLVersion === 1) {
  12157. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12158. }
  12159. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12160. }
  12161. // Checks if some of the format renders first to allow the use of webgl inspector.
  12162. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12163. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12164. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12165. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12166. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12167. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12168. if (this._webGLVersion > 1) {
  12169. this._gl.HALF_FLOAT_OES = 0x140B;
  12170. }
  12171. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12172. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12173. // Draw buffers
  12174. if (this._webGLVersion > 1) {
  12175. this._caps.drawBuffersExtension = true;
  12176. }
  12177. else {
  12178. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12179. if (drawBuffersExtension !== null) {
  12180. this._caps.drawBuffersExtension = true;
  12181. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12182. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12183. for (var i = 0; i < 16; i++) {
  12184. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12185. }
  12186. }
  12187. else {
  12188. this._caps.drawBuffersExtension = false;
  12189. }
  12190. }
  12191. // Depth Texture
  12192. if (this._webGLVersion > 1) {
  12193. this._caps.depthTextureExtension = true;
  12194. }
  12195. else {
  12196. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12197. if (depthTextureExtension != null) {
  12198. this._caps.depthTextureExtension = true;
  12199. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12200. }
  12201. }
  12202. // Vertex array object
  12203. if (this._webGLVersion > 1) {
  12204. this._caps.vertexArrayObject = true;
  12205. }
  12206. else {
  12207. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12208. if (vertexArrayObjectExtension != null) {
  12209. this._caps.vertexArrayObject = true;
  12210. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12211. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12212. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12213. }
  12214. else {
  12215. this._caps.vertexArrayObject = false;
  12216. }
  12217. }
  12218. // Instances count
  12219. if (this._webGLVersion > 1) {
  12220. this._caps.instancedArrays = true;
  12221. }
  12222. else {
  12223. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12224. if (instanceExtension != null) {
  12225. this._caps.instancedArrays = true;
  12226. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12227. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12228. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12229. }
  12230. else {
  12231. this._caps.instancedArrays = false;
  12232. }
  12233. }
  12234. // Intelligently add supported compressed formats in order to check for.
  12235. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12236. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12237. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12238. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12239. if (this._caps.astc)
  12240. this.texturesSupported.push('-astc.ktx');
  12241. if (this._caps.s3tc)
  12242. this.texturesSupported.push('-dxt.ktx');
  12243. if (this._caps.pvrtc)
  12244. this.texturesSupported.push('-pvrtc.ktx');
  12245. if (this._caps.etc2)
  12246. this.texturesSupported.push('-etc2.ktx');
  12247. if (this._caps.etc1)
  12248. this.texturesSupported.push('-etc1.ktx');
  12249. if (this._gl.getShaderPrecisionFormat) {
  12250. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12251. if (highp) {
  12252. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12253. }
  12254. }
  12255. // Depth buffer
  12256. this.setDepthBuffer(true);
  12257. this.setDepthFunctionToLessOrEqual();
  12258. this.setDepthWrite(true);
  12259. // Texture maps
  12260. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12261. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12262. this._nextFreeTextureSlots.push(slot);
  12263. }
  12264. };
  12265. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12266. /**
  12267. * Gets version of the current webGL context
  12268. */
  12269. get: function () {
  12270. return this._webGLVersion;
  12271. },
  12272. enumerable: true,
  12273. configurable: true
  12274. });
  12275. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12276. /**
  12277. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12278. */
  12279. get: function () {
  12280. return this._isStencilEnable;
  12281. },
  12282. enumerable: true,
  12283. configurable: true
  12284. });
  12285. Engine.prototype._prepareWorkingCanvas = function () {
  12286. if (this._workingCanvas) {
  12287. return;
  12288. }
  12289. this._workingCanvas = document.createElement("canvas");
  12290. var context = this._workingCanvas.getContext("2d");
  12291. if (context) {
  12292. this._workingContext = context;
  12293. }
  12294. };
  12295. /**
  12296. * Reset the texture cache to empty state
  12297. */
  12298. Engine.prototype.resetTextureCache = function () {
  12299. for (var key in this._boundTexturesCache) {
  12300. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12301. continue;
  12302. }
  12303. var boundTexture = this._boundTexturesCache[key];
  12304. if (boundTexture) {
  12305. this._removeDesignatedSlot(boundTexture);
  12306. }
  12307. this._boundTexturesCache[key] = null;
  12308. }
  12309. if (!this.disableTextureBindingOptimization) {
  12310. this._nextFreeTextureSlots = [];
  12311. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12312. this._nextFreeTextureSlots.push(slot);
  12313. }
  12314. }
  12315. this._currentTextureChannel = -1;
  12316. };
  12317. /**
  12318. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12319. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12320. * @returns true if engine is in deterministic lock step mode
  12321. */
  12322. Engine.prototype.isDeterministicLockStep = function () {
  12323. return this._deterministicLockstep;
  12324. };
  12325. /**
  12326. * Gets the max steps when engine is running in deterministic lock step
  12327. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12328. * @returns the max steps
  12329. */
  12330. Engine.prototype.getLockstepMaxSteps = function () {
  12331. return this._lockstepMaxSteps;
  12332. };
  12333. /**
  12334. * Gets an object containing information about the current webGL context
  12335. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12336. */
  12337. Engine.prototype.getGlInfo = function () {
  12338. return {
  12339. vendor: this._glVendor,
  12340. renderer: this._glRenderer,
  12341. version: this._glVersion
  12342. };
  12343. };
  12344. /**
  12345. * Gets current aspect ratio
  12346. * @param camera defines the camera to use to get the aspect ratio
  12347. * @param useScreen defines if screen size must be used (or the current render target if any)
  12348. * @returns a number defining the aspect ratio
  12349. */
  12350. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12351. if (useScreen === void 0) { useScreen = false; }
  12352. var viewport = camera.viewport;
  12353. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12354. };
  12355. /**
  12356. * Gets the current render width
  12357. * @param useScreen defines if screen size must be used (or the current render target if any)
  12358. * @returns a number defining the current render width
  12359. */
  12360. Engine.prototype.getRenderWidth = function (useScreen) {
  12361. if (useScreen === void 0) { useScreen = false; }
  12362. if (!useScreen && this._currentRenderTarget) {
  12363. return this._currentRenderTarget.width;
  12364. }
  12365. return this._gl.drawingBufferWidth;
  12366. };
  12367. /**
  12368. * Gets the current render height
  12369. * @param useScreen defines if screen size must be used (or the current render target if any)
  12370. * @returns a number defining the current render height
  12371. */
  12372. Engine.prototype.getRenderHeight = function (useScreen) {
  12373. if (useScreen === void 0) { useScreen = false; }
  12374. if (!useScreen && this._currentRenderTarget) {
  12375. return this._currentRenderTarget.height;
  12376. }
  12377. return this._gl.drawingBufferHeight;
  12378. };
  12379. /**
  12380. * Gets the HTML canvas attached with the current webGL context
  12381. * @returns a HTML canvas
  12382. */
  12383. Engine.prototype.getRenderingCanvas = function () {
  12384. return this._renderingCanvas;
  12385. };
  12386. /**
  12387. * Gets the client rect of the HTML canvas attached with the current webGL context
  12388. * @returns a client rectanglee
  12389. */
  12390. Engine.prototype.getRenderingCanvasClientRect = function () {
  12391. if (!this._renderingCanvas) {
  12392. return null;
  12393. }
  12394. return this._renderingCanvas.getBoundingClientRect();
  12395. };
  12396. /**
  12397. * Defines the hardware scaling level.
  12398. * By default the hardware scaling level is computed from the window device ratio.
  12399. * 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.
  12400. * @param level defines the level to use
  12401. */
  12402. Engine.prototype.setHardwareScalingLevel = function (level) {
  12403. this._hardwareScalingLevel = level;
  12404. this.resize();
  12405. };
  12406. /**
  12407. * Gets the current hardware scaling level.
  12408. * By default the hardware scaling level is computed from the window device ratio.
  12409. * 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.
  12410. * @returns a number indicating the current hardware scaling level
  12411. */
  12412. Engine.prototype.getHardwareScalingLevel = function () {
  12413. return this._hardwareScalingLevel;
  12414. };
  12415. /**
  12416. * Gets the list of loaded textures
  12417. * @returns an array containing all loaded textures
  12418. */
  12419. Engine.prototype.getLoadedTexturesCache = function () {
  12420. return this._internalTexturesCache;
  12421. };
  12422. /**
  12423. * Gets the object containing all engine capabilities
  12424. * @returns the EngineCapabilities object
  12425. */
  12426. Engine.prototype.getCaps = function () {
  12427. return this._caps;
  12428. };
  12429. Object.defineProperty(Engine.prototype, "drawCalls", {
  12430. /** @hidden */
  12431. get: function () {
  12432. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12433. return 0;
  12434. },
  12435. enumerable: true,
  12436. configurable: true
  12437. });
  12438. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12439. /** @hidden */
  12440. get: function () {
  12441. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12442. return null;
  12443. },
  12444. enumerable: true,
  12445. configurable: true
  12446. });
  12447. /**
  12448. * Gets the current depth function
  12449. * @returns a number defining the depth function
  12450. */
  12451. Engine.prototype.getDepthFunction = function () {
  12452. return this._depthCullingState.depthFunc;
  12453. };
  12454. /**
  12455. * Sets the current depth function
  12456. * @param depthFunc defines the function to use
  12457. */
  12458. Engine.prototype.setDepthFunction = function (depthFunc) {
  12459. this._depthCullingState.depthFunc = depthFunc;
  12460. };
  12461. /**
  12462. * Sets the current depth function to GREATER
  12463. */
  12464. Engine.prototype.setDepthFunctionToGreater = function () {
  12465. this._depthCullingState.depthFunc = this._gl.GREATER;
  12466. };
  12467. /**
  12468. * Sets the current depth function to GEQUAL
  12469. */
  12470. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12471. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12472. };
  12473. /**
  12474. * Sets the current depth function to LESS
  12475. */
  12476. Engine.prototype.setDepthFunctionToLess = function () {
  12477. this._depthCullingState.depthFunc = this._gl.LESS;
  12478. };
  12479. /**
  12480. * Sets the current depth function to LEQUAL
  12481. */
  12482. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12483. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12484. };
  12485. /**
  12486. * Gets a boolean indicating if stencil buffer is enabled
  12487. * @returns the current stencil buffer state
  12488. */
  12489. Engine.prototype.getStencilBuffer = function () {
  12490. return this._stencilState.stencilTest;
  12491. };
  12492. /**
  12493. * Enable or disable the stencil buffer
  12494. * @param enable defines if the stencil buffer must be enabled or disabled
  12495. */
  12496. Engine.prototype.setStencilBuffer = function (enable) {
  12497. this._stencilState.stencilTest = enable;
  12498. };
  12499. /**
  12500. * Gets the current stencil mask
  12501. * @returns a number defining the new stencil mask to use
  12502. */
  12503. Engine.prototype.getStencilMask = function () {
  12504. return this._stencilState.stencilMask;
  12505. };
  12506. /**
  12507. * Sets the current stencil mask
  12508. * @param mask defines the new stencil mask to use
  12509. */
  12510. Engine.prototype.setStencilMask = function (mask) {
  12511. this._stencilState.stencilMask = mask;
  12512. };
  12513. /**
  12514. * Gets the current stencil function
  12515. * @returns a number defining the stencil function to use
  12516. */
  12517. Engine.prototype.getStencilFunction = function () {
  12518. return this._stencilState.stencilFunc;
  12519. };
  12520. /**
  12521. * Gets the current stencil reference value
  12522. * @returns a number defining the stencil reference value to use
  12523. */
  12524. Engine.prototype.getStencilFunctionReference = function () {
  12525. return this._stencilState.stencilFuncRef;
  12526. };
  12527. /**
  12528. * Gets the current stencil mask
  12529. * @returns a number defining the stencil mask to use
  12530. */
  12531. Engine.prototype.getStencilFunctionMask = function () {
  12532. return this._stencilState.stencilFuncMask;
  12533. };
  12534. /**
  12535. * Sets the current stencil function
  12536. * @param stencilFunc defines the new stencil function to use
  12537. */
  12538. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12539. this._stencilState.stencilFunc = stencilFunc;
  12540. };
  12541. /**
  12542. * Sets the current stencil reference
  12543. * @param reference defines the new stencil reference to use
  12544. */
  12545. Engine.prototype.setStencilFunctionReference = function (reference) {
  12546. this._stencilState.stencilFuncRef = reference;
  12547. };
  12548. /**
  12549. * Sets the current stencil mask
  12550. * @param mask defines the new stencil mask to use
  12551. */
  12552. Engine.prototype.setStencilFunctionMask = function (mask) {
  12553. this._stencilState.stencilFuncMask = mask;
  12554. };
  12555. /**
  12556. * Gets the current stencil operation when stencil fails
  12557. * @returns a number defining stencil operation to use when stencil fails
  12558. */
  12559. Engine.prototype.getStencilOperationFail = function () {
  12560. return this._stencilState.stencilOpStencilFail;
  12561. };
  12562. /**
  12563. * Gets the current stencil operation when depth fails
  12564. * @returns a number defining stencil operation to use when depth fails
  12565. */
  12566. Engine.prototype.getStencilOperationDepthFail = function () {
  12567. return this._stencilState.stencilOpDepthFail;
  12568. };
  12569. /**
  12570. * Gets the current stencil operation when stencil passes
  12571. * @returns a number defining stencil operation to use when stencil passes
  12572. */
  12573. Engine.prototype.getStencilOperationPass = function () {
  12574. return this._stencilState.stencilOpStencilDepthPass;
  12575. };
  12576. /**
  12577. * Sets the stencil operation to use when stencil fails
  12578. * @param operation defines the stencil operation to use when stencil fails
  12579. */
  12580. Engine.prototype.setStencilOperationFail = function (operation) {
  12581. this._stencilState.stencilOpStencilFail = operation;
  12582. };
  12583. /**
  12584. * Sets the stencil operation to use when depth fails
  12585. * @param operation defines the stencil operation to use when depth fails
  12586. */
  12587. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12588. this._stencilState.stencilOpDepthFail = operation;
  12589. };
  12590. /**
  12591. * Sets the stencil operation to use when stencil passes
  12592. * @param operation defines the stencil operation to use when stencil passes
  12593. */
  12594. Engine.prototype.setStencilOperationPass = function (operation) {
  12595. this._stencilState.stencilOpStencilDepthPass = operation;
  12596. };
  12597. /**
  12598. * Sets a boolean indicating if the dithering state is enabled or disabled
  12599. * @param value defines the dithering state
  12600. */
  12601. Engine.prototype.setDitheringState = function (value) {
  12602. if (value) {
  12603. this._gl.enable(this._gl.DITHER);
  12604. }
  12605. else {
  12606. this._gl.disable(this._gl.DITHER);
  12607. }
  12608. };
  12609. /**
  12610. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12611. * @param value defines the rasterizer state
  12612. */
  12613. Engine.prototype.setRasterizerState = function (value) {
  12614. if (value) {
  12615. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12616. }
  12617. else {
  12618. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12619. }
  12620. };
  12621. /**
  12622. * stop executing a render loop function and remove it from the execution array
  12623. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12624. */
  12625. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12626. if (!renderFunction) {
  12627. this._activeRenderLoops = [];
  12628. return;
  12629. }
  12630. var index = this._activeRenderLoops.indexOf(renderFunction);
  12631. if (index >= 0) {
  12632. this._activeRenderLoops.splice(index, 1);
  12633. }
  12634. };
  12635. /** @hidden */
  12636. Engine.prototype._renderLoop = function () {
  12637. if (!this._contextWasLost) {
  12638. var shouldRender = true;
  12639. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12640. shouldRender = false;
  12641. }
  12642. if (shouldRender) {
  12643. // Start new frame
  12644. this.beginFrame();
  12645. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12646. var renderFunction = this._activeRenderLoops[index];
  12647. renderFunction();
  12648. }
  12649. // Present
  12650. this.endFrame();
  12651. }
  12652. }
  12653. if (this._activeRenderLoops.length > 0) {
  12654. // Register new frame
  12655. var requester = null;
  12656. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12657. requester = this._vrDisplay;
  12658. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12659. }
  12660. else {
  12661. this._renderingQueueLaunched = false;
  12662. }
  12663. };
  12664. /**
  12665. * Register and execute a render loop. The engine can have more than one render function
  12666. * @param renderFunction defines the function to continuously execute
  12667. */
  12668. Engine.prototype.runRenderLoop = function (renderFunction) {
  12669. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12670. return;
  12671. }
  12672. this._activeRenderLoops.push(renderFunction);
  12673. if (!this._renderingQueueLaunched) {
  12674. this._renderingQueueLaunched = true;
  12675. this._bindedRenderFunction = this._renderLoop.bind(this);
  12676. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12677. }
  12678. };
  12679. /**
  12680. * Toggle full screen mode
  12681. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12682. * @param options defines an option object to be sent to the requestFullscreen function
  12683. */
  12684. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12685. if (this.isFullscreen) {
  12686. BABYLON.Tools.ExitFullscreen();
  12687. }
  12688. else {
  12689. this._pointerLockRequested = requestPointerLock;
  12690. if (this._renderingCanvas) {
  12691. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12692. }
  12693. }
  12694. };
  12695. /**
  12696. * Clear the current render buffer or the current render target (if any is set up)
  12697. * @param color defines the color to use
  12698. * @param backBuffer defines if the back buffer must be cleared
  12699. * @param depth defines if the depth buffer must be cleared
  12700. * @param stencil defines if the stencil buffer must be cleared
  12701. */
  12702. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12703. if (stencil === void 0) { stencil = false; }
  12704. this.applyStates();
  12705. var mode = 0;
  12706. if (backBuffer && color) {
  12707. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12708. mode |= this._gl.COLOR_BUFFER_BIT;
  12709. }
  12710. if (depth) {
  12711. this._gl.clearDepth(1.0);
  12712. mode |= this._gl.DEPTH_BUFFER_BIT;
  12713. }
  12714. if (stencil) {
  12715. this._gl.clearStencil(0);
  12716. mode |= this._gl.STENCIL_BUFFER_BIT;
  12717. }
  12718. this._gl.clear(mode);
  12719. };
  12720. /**
  12721. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12722. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12723. * @param y defines the y-coordinate of the corner of the clear rectangle
  12724. * @param width defines the width of the clear rectangle
  12725. * @param height defines the height of the clear rectangle
  12726. * @param clearColor defines the clear color
  12727. */
  12728. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12729. var gl = this._gl;
  12730. // Save state
  12731. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12732. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12733. // Change state
  12734. gl.enable(gl.SCISSOR_TEST);
  12735. gl.scissor(x, y, width, height);
  12736. // Clear
  12737. this.clear(clearColor, true, true, true);
  12738. // Restore state
  12739. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12740. if (curScissor === true) {
  12741. gl.enable(gl.SCISSOR_TEST);
  12742. }
  12743. else {
  12744. gl.disable(gl.SCISSOR_TEST);
  12745. }
  12746. };
  12747. /**
  12748. * Set the WebGL's viewport
  12749. * @param viewport defines the viewport element to be used
  12750. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12751. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12752. */
  12753. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12754. var width = requiredWidth || this.getRenderWidth();
  12755. var height = requiredHeight || this.getRenderHeight();
  12756. var x = viewport.x || 0;
  12757. var y = viewport.y || 0;
  12758. this._cachedViewport = viewport;
  12759. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12760. };
  12761. /**
  12762. * Directly set the WebGL Viewport
  12763. * @param x defines the x coordinate of the viewport (in screen space)
  12764. * @param y defines the y coordinate of the viewport (in screen space)
  12765. * @param width defines the width of the viewport (in screen space)
  12766. * @param height defines the height of the viewport (in screen space)
  12767. * @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
  12768. */
  12769. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12770. var currentViewport = this._cachedViewport;
  12771. this._cachedViewport = null;
  12772. this._gl.viewport(x, y, width, height);
  12773. return currentViewport;
  12774. };
  12775. /**
  12776. * Begin a new frame
  12777. */
  12778. Engine.prototype.beginFrame = function () {
  12779. this.onBeginFrameObservable.notifyObservers(this);
  12780. this._measureFps();
  12781. };
  12782. /**
  12783. * Enf the current frame
  12784. */
  12785. Engine.prototype.endFrame = function () {
  12786. // Force a flush in case we are using a bad OS.
  12787. if (this._badOS) {
  12788. this.flushFramebuffer();
  12789. }
  12790. // Submit frame to the vr device, if enabled
  12791. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12792. // TODO: We should only submit the frame if we read frameData successfully.
  12793. this._vrDisplay.submitFrame();
  12794. }
  12795. this.onEndFrameObservable.notifyObservers(this);
  12796. };
  12797. /**
  12798. * Resize the view according to the canvas' size
  12799. */
  12800. Engine.prototype.resize = function () {
  12801. // We're not resizing the size of the canvas while in VR mode & presenting
  12802. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12803. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12804. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12805. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12806. }
  12807. };
  12808. /**
  12809. * Force a specific size of the canvas
  12810. * @param width defines the new canvas' width
  12811. * @param height defines the new canvas' height
  12812. */
  12813. Engine.prototype.setSize = function (width, height) {
  12814. if (!this._renderingCanvas) {
  12815. return;
  12816. }
  12817. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12818. return;
  12819. }
  12820. this._renderingCanvas.width = width;
  12821. this._renderingCanvas.height = height;
  12822. for (var index = 0; index < this.scenes.length; index++) {
  12823. var scene = this.scenes[index];
  12824. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12825. var cam = scene.cameras[camIndex];
  12826. cam._currentRenderId = 0;
  12827. }
  12828. }
  12829. if (this.onResizeObservable.hasObservers) {
  12830. this.onResizeObservable.notifyObservers(this);
  12831. }
  12832. };
  12833. // WebVR functions
  12834. /**
  12835. * Gets a boolean indicating if a webVR device was detected
  12836. * @returns true if a webVR device was detected
  12837. */
  12838. Engine.prototype.isVRDevicePresent = function () {
  12839. return !!this._vrDisplay;
  12840. };
  12841. /**
  12842. * Gets the current webVR device
  12843. * @returns the current webVR device (or null)
  12844. */
  12845. Engine.prototype.getVRDevice = function () {
  12846. return this._vrDisplay;
  12847. };
  12848. /**
  12849. * Initializes a webVR display and starts listening to display change events
  12850. * The onVRDisplayChangedObservable will be notified upon these changes
  12851. * @returns The onVRDisplayChangedObservable
  12852. */
  12853. Engine.prototype.initWebVR = function () {
  12854. this.initWebVRAsync();
  12855. return this.onVRDisplayChangedObservable;
  12856. };
  12857. /**
  12858. * Initializes a webVR display and starts listening to display change events
  12859. * The onVRDisplayChangedObservable will be notified upon these changes
  12860. * @returns A promise containing a VRDisplay and if vr is supported
  12861. */
  12862. Engine.prototype.initWebVRAsync = function () {
  12863. var _this = this;
  12864. var notifyObservers = function () {
  12865. var eventArgs = {
  12866. vrDisplay: _this._vrDisplay,
  12867. vrSupported: _this._vrSupported
  12868. };
  12869. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12870. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12871. };
  12872. if (!this._onVrDisplayConnect) {
  12873. this._onVrDisplayConnect = function (event) {
  12874. _this._vrDisplay = event.display;
  12875. notifyObservers();
  12876. };
  12877. this._onVrDisplayDisconnect = function () {
  12878. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12879. _this._vrDisplay = undefined;
  12880. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12881. notifyObservers();
  12882. };
  12883. this._onVrDisplayPresentChange = function () {
  12884. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12885. };
  12886. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12887. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12888. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12889. }
  12890. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12891. this._webVRInitPromise.then(notifyObservers);
  12892. return this._webVRInitPromise;
  12893. };
  12894. /**
  12895. * Call this function to switch to webVR mode
  12896. * Will do nothing if webVR is not supported or if there is no webVR device
  12897. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12898. */
  12899. Engine.prototype.enableVR = function () {
  12900. var _this = this;
  12901. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12902. var onResolved = function () {
  12903. _this.onVRRequestPresentComplete.notifyObservers(true);
  12904. _this._onVRFullScreenTriggered();
  12905. };
  12906. var onRejected = function () {
  12907. _this.onVRRequestPresentComplete.notifyObservers(false);
  12908. };
  12909. this.onVRRequestPresentStart.notifyObservers(this);
  12910. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12911. }
  12912. };
  12913. /**
  12914. * Call this function to leave webVR mode
  12915. * Will do nothing if webVR is not supported or if there is no webVR device
  12916. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12917. */
  12918. Engine.prototype.disableVR = function () {
  12919. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12920. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12921. }
  12922. };
  12923. Engine.prototype._getVRDisplaysAsync = function () {
  12924. var _this = this;
  12925. return new Promise(function (res, rej) {
  12926. if (navigator.getVRDisplays) {
  12927. navigator.getVRDisplays().then(function (devices) {
  12928. _this._vrSupported = true;
  12929. // note that devices may actually be an empty array. This is fine;
  12930. // we expect this._vrDisplay to be undefined in this case.
  12931. _this._vrDisplay = devices[0];
  12932. res({
  12933. vrDisplay: _this._vrDisplay,
  12934. vrSupported: _this._vrSupported
  12935. });
  12936. });
  12937. }
  12938. else {
  12939. _this._vrDisplay = undefined;
  12940. _this._vrSupported = false;
  12941. res({
  12942. vrDisplay: _this._vrDisplay,
  12943. vrSupported: _this._vrSupported
  12944. });
  12945. }
  12946. });
  12947. };
  12948. /**
  12949. * Binds the frame buffer to the specified texture.
  12950. * @param texture The texture to render to or null for the default canvas
  12951. * @param faceIndex The face of the texture to render to in case of cube texture
  12952. * @param requiredWidth The width of the target to render to
  12953. * @param requiredHeight The height of the target to render to
  12954. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12955. * @param depthStencilTexture The depth stencil texture to use to render
  12956. */
  12957. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12958. if (this._currentRenderTarget) {
  12959. this.unBindFramebuffer(this._currentRenderTarget);
  12960. }
  12961. this._currentRenderTarget = texture;
  12962. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12963. var gl = this._gl;
  12964. if (texture.isCube) {
  12965. if (faceIndex === undefined) {
  12966. faceIndex = 0;
  12967. }
  12968. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12969. if (depthStencilTexture) {
  12970. if (depthStencilTexture._generateStencilBuffer) {
  12971. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12972. }
  12973. else {
  12974. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12975. }
  12976. }
  12977. }
  12978. if (this._cachedViewport && !forceFullscreenViewport) {
  12979. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12980. }
  12981. else {
  12982. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12983. }
  12984. this.wipeCaches();
  12985. };
  12986. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12987. if (this._currentFramebuffer !== framebuffer) {
  12988. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12989. this._currentFramebuffer = framebuffer;
  12990. }
  12991. };
  12992. /**
  12993. * Unbind the current render target texture from the webGL context
  12994. * @param texture defines the render target texture to unbind
  12995. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12996. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12997. */
  12998. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12999. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13000. this._currentRenderTarget = null;
  13001. // If MSAA, we need to bitblt back to main texture
  13002. var gl = this._gl;
  13003. if (texture._MSAAFramebuffer) {
  13004. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13005. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13006. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13007. }
  13008. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13009. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13010. gl.generateMipmap(gl.TEXTURE_2D);
  13011. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13012. }
  13013. if (onBeforeUnbind) {
  13014. if (texture._MSAAFramebuffer) {
  13015. // Bind the correct framebuffer
  13016. this.bindUnboundFramebuffer(texture._framebuffer);
  13017. }
  13018. onBeforeUnbind();
  13019. }
  13020. this.bindUnboundFramebuffer(null);
  13021. };
  13022. /**
  13023. * Unbind a list of render target textures from the webGL context
  13024. * This is used only when drawBuffer extension or webGL2 are active
  13025. * @param textures defines the render target textures to unbind
  13026. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13027. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13028. */
  13029. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13030. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13031. this._currentRenderTarget = null;
  13032. // If MSAA, we need to bitblt back to main texture
  13033. var gl = this._gl;
  13034. if (textures[0]._MSAAFramebuffer) {
  13035. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13036. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13037. var attachments = textures[0]._attachments;
  13038. if (!attachments) {
  13039. attachments = new Array(textures.length);
  13040. textures[0]._attachments = attachments;
  13041. }
  13042. for (var i = 0; i < textures.length; i++) {
  13043. var texture = textures[i];
  13044. for (var j = 0; j < attachments.length; j++) {
  13045. attachments[j] = gl.NONE;
  13046. }
  13047. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13048. gl.readBuffer(attachments[i]);
  13049. gl.drawBuffers(attachments);
  13050. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13051. }
  13052. for (var i = 0; i < attachments.length; i++) {
  13053. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13054. }
  13055. gl.drawBuffers(attachments);
  13056. }
  13057. for (var i = 0; i < textures.length; i++) {
  13058. var texture = textures[i];
  13059. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13060. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13061. gl.generateMipmap(gl.TEXTURE_2D);
  13062. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13063. }
  13064. }
  13065. if (onBeforeUnbind) {
  13066. if (textures[0]._MSAAFramebuffer) {
  13067. // Bind the correct framebuffer
  13068. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13069. }
  13070. onBeforeUnbind();
  13071. }
  13072. this.bindUnboundFramebuffer(null);
  13073. };
  13074. /**
  13075. * Force the mipmap generation for the given render target texture
  13076. * @param texture defines the render target texture to use
  13077. */
  13078. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13079. if (texture.generateMipMaps) {
  13080. var gl = this._gl;
  13081. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13082. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13083. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13084. }
  13085. };
  13086. /**
  13087. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13088. */
  13089. Engine.prototype.flushFramebuffer = function () {
  13090. this._gl.flush();
  13091. };
  13092. /**
  13093. * Unbind the current render target and bind the default framebuffer
  13094. */
  13095. Engine.prototype.restoreDefaultFramebuffer = function () {
  13096. if (this._currentRenderTarget) {
  13097. this.unBindFramebuffer(this._currentRenderTarget);
  13098. }
  13099. else {
  13100. this.bindUnboundFramebuffer(null);
  13101. }
  13102. if (this._cachedViewport) {
  13103. this.setViewport(this._cachedViewport);
  13104. }
  13105. this.wipeCaches();
  13106. };
  13107. // UBOs
  13108. /**
  13109. * Create an uniform buffer
  13110. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13111. * @param elements defines the content of the uniform buffer
  13112. * @returns the webGL uniform buffer
  13113. */
  13114. Engine.prototype.createUniformBuffer = function (elements) {
  13115. var ubo = this._gl.createBuffer();
  13116. if (!ubo) {
  13117. throw new Error("Unable to create uniform buffer");
  13118. }
  13119. this.bindUniformBuffer(ubo);
  13120. if (elements instanceof Float32Array) {
  13121. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13122. }
  13123. else {
  13124. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13125. }
  13126. this.bindUniformBuffer(null);
  13127. ubo.references = 1;
  13128. return ubo;
  13129. };
  13130. /**
  13131. * Create a dynamic uniform buffer
  13132. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13133. * @param elements defines the content of the uniform buffer
  13134. * @returns the webGL uniform buffer
  13135. */
  13136. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13137. var ubo = this._gl.createBuffer();
  13138. if (!ubo) {
  13139. throw new Error("Unable to create dynamic uniform buffer");
  13140. }
  13141. this.bindUniformBuffer(ubo);
  13142. if (elements instanceof Float32Array) {
  13143. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13144. }
  13145. else {
  13146. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13147. }
  13148. this.bindUniformBuffer(null);
  13149. ubo.references = 1;
  13150. return ubo;
  13151. };
  13152. /**
  13153. * Update an existing uniform buffer
  13154. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13155. * @param uniformBuffer defines the target uniform buffer
  13156. * @param elements defines the content to update
  13157. * @param offset defines the offset in the uniform buffer where update should start
  13158. * @param count defines the size of the data to update
  13159. */
  13160. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13161. this.bindUniformBuffer(uniformBuffer);
  13162. if (offset === undefined) {
  13163. offset = 0;
  13164. }
  13165. if (count === undefined) {
  13166. if (elements instanceof Float32Array) {
  13167. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13168. }
  13169. else {
  13170. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13171. }
  13172. }
  13173. else {
  13174. if (elements instanceof Float32Array) {
  13175. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13176. }
  13177. else {
  13178. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13179. }
  13180. }
  13181. this.bindUniformBuffer(null);
  13182. };
  13183. // VBOs
  13184. Engine.prototype._resetVertexBufferBinding = function () {
  13185. this.bindArrayBuffer(null);
  13186. this._cachedVertexBuffers = null;
  13187. };
  13188. /**
  13189. * Creates a vertex buffer
  13190. * @param data the data for the vertex buffer
  13191. * @returns the new WebGL static buffer
  13192. */
  13193. Engine.prototype.createVertexBuffer = function (data) {
  13194. var vbo = this._gl.createBuffer();
  13195. if (!vbo) {
  13196. throw new Error("Unable to create vertex buffer");
  13197. }
  13198. this.bindArrayBuffer(vbo);
  13199. if (data instanceof Array) {
  13200. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13201. }
  13202. else {
  13203. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13204. }
  13205. this._resetVertexBufferBinding();
  13206. vbo.references = 1;
  13207. return vbo;
  13208. };
  13209. /**
  13210. * Creates a dynamic vertex buffer
  13211. * @param data the data for the dynamic vertex buffer
  13212. * @returns the new WebGL dynamic buffer
  13213. */
  13214. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13215. var vbo = this._gl.createBuffer();
  13216. if (!vbo) {
  13217. throw new Error("Unable to create dynamic vertex buffer");
  13218. }
  13219. this.bindArrayBuffer(vbo);
  13220. if (data instanceof Array) {
  13221. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13222. }
  13223. else {
  13224. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13225. }
  13226. this._resetVertexBufferBinding();
  13227. vbo.references = 1;
  13228. return vbo;
  13229. };
  13230. /**
  13231. * Update a dynamic index buffer
  13232. * @param indexBuffer defines the target index buffer
  13233. * @param indices defines the data to update
  13234. * @param offset defines the offset in the target index buffer where update should start
  13235. */
  13236. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13237. if (offset === void 0) { offset = 0; }
  13238. // Force cache update
  13239. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13240. this.bindIndexBuffer(indexBuffer);
  13241. var arrayBuffer;
  13242. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13243. arrayBuffer = indices;
  13244. }
  13245. else {
  13246. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13247. }
  13248. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13249. this._resetIndexBufferBinding();
  13250. };
  13251. /**
  13252. * Updates a dynamic vertex buffer.
  13253. * @param vertexBuffer the vertex buffer to update
  13254. * @param data the data used to update the vertex buffer
  13255. * @param byteOffset the byte offset of the data
  13256. * @param byteLength the byte length of the data
  13257. */
  13258. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13259. this.bindArrayBuffer(vertexBuffer);
  13260. if (byteOffset === undefined) {
  13261. byteOffset = 0;
  13262. }
  13263. if (byteLength === undefined) {
  13264. if (data instanceof Array) {
  13265. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13266. }
  13267. else {
  13268. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13269. }
  13270. }
  13271. else {
  13272. if (data instanceof Array) {
  13273. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13274. }
  13275. else {
  13276. if (data instanceof ArrayBuffer) {
  13277. data = new Uint8Array(data, byteOffset, byteLength);
  13278. }
  13279. else {
  13280. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13281. }
  13282. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13283. }
  13284. }
  13285. this._resetVertexBufferBinding();
  13286. };
  13287. Engine.prototype._resetIndexBufferBinding = function () {
  13288. this.bindIndexBuffer(null);
  13289. this._cachedIndexBuffer = null;
  13290. };
  13291. /**
  13292. * Creates a new index buffer
  13293. * @param indices defines the content of the index buffer
  13294. * @param updatable defines if the index buffer must be updatable
  13295. * @returns a new webGL buffer
  13296. */
  13297. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13298. var vbo = this._gl.createBuffer();
  13299. if (!vbo) {
  13300. throw new Error("Unable to create index buffer");
  13301. }
  13302. this.bindIndexBuffer(vbo);
  13303. // Check for 32 bits indices
  13304. var arrayBuffer;
  13305. var need32Bits = false;
  13306. if (indices instanceof Uint16Array) {
  13307. arrayBuffer = indices;
  13308. }
  13309. else {
  13310. //check 32 bit support
  13311. if (this._caps.uintIndices) {
  13312. if (indices instanceof Uint32Array) {
  13313. arrayBuffer = indices;
  13314. need32Bits = true;
  13315. }
  13316. else {
  13317. //number[] or Int32Array, check if 32 bit is necessary
  13318. for (var index = 0; index < indices.length; index++) {
  13319. if (indices[index] > 65535) {
  13320. need32Bits = true;
  13321. break;
  13322. }
  13323. }
  13324. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13325. }
  13326. }
  13327. else {
  13328. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13329. arrayBuffer = new Uint16Array(indices);
  13330. }
  13331. }
  13332. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13333. this._resetIndexBufferBinding();
  13334. vbo.references = 1;
  13335. vbo.is32Bits = need32Bits;
  13336. return vbo;
  13337. };
  13338. /**
  13339. * Bind a webGL buffer to the webGL context
  13340. * @param buffer defines the buffer to bind
  13341. */
  13342. Engine.prototype.bindArrayBuffer = function (buffer) {
  13343. if (!this._vaoRecordInProgress) {
  13344. this._unbindVertexArrayObject();
  13345. }
  13346. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13347. };
  13348. /**
  13349. * Bind an uniform buffer to the current webGL context
  13350. * @param buffer defines the buffer to bind
  13351. */
  13352. Engine.prototype.bindUniformBuffer = function (buffer) {
  13353. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13354. };
  13355. /**
  13356. * Bind a buffer to the current webGL context at a given location
  13357. * @param buffer defines the buffer to bind
  13358. * @param location defines the index where to bind the buffer
  13359. */
  13360. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13361. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13362. };
  13363. /**
  13364. * Bind a specific block at a given index in a specific shader program
  13365. * @param shaderProgram defines the shader program
  13366. * @param blockName defines the block name
  13367. * @param index defines the index where to bind the block
  13368. */
  13369. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13370. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13371. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13372. };
  13373. ;
  13374. Engine.prototype.bindIndexBuffer = function (buffer) {
  13375. if (!this._vaoRecordInProgress) {
  13376. this._unbindVertexArrayObject();
  13377. }
  13378. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13379. };
  13380. Engine.prototype.bindBuffer = function (buffer, target) {
  13381. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13382. this._gl.bindBuffer(target, buffer);
  13383. this._currentBoundBuffer[target] = buffer;
  13384. }
  13385. };
  13386. /**
  13387. * update the bound buffer with the given data
  13388. * @param data defines the data to update
  13389. */
  13390. Engine.prototype.updateArrayBuffer = function (data) {
  13391. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13392. };
  13393. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13394. var pointer = this._currentBufferPointers[indx];
  13395. var changed = false;
  13396. if (!pointer.active) {
  13397. changed = true;
  13398. pointer.active = true;
  13399. pointer.index = indx;
  13400. pointer.size = size;
  13401. pointer.type = type;
  13402. pointer.normalized = normalized;
  13403. pointer.stride = stride;
  13404. pointer.offset = offset;
  13405. pointer.buffer = buffer;
  13406. }
  13407. else {
  13408. if (pointer.buffer !== buffer) {
  13409. pointer.buffer = buffer;
  13410. changed = true;
  13411. }
  13412. if (pointer.size !== size) {
  13413. pointer.size = size;
  13414. changed = true;
  13415. }
  13416. if (pointer.type !== type) {
  13417. pointer.type = type;
  13418. changed = true;
  13419. }
  13420. if (pointer.normalized !== normalized) {
  13421. pointer.normalized = normalized;
  13422. changed = true;
  13423. }
  13424. if (pointer.stride !== stride) {
  13425. pointer.stride = stride;
  13426. changed = true;
  13427. }
  13428. if (pointer.offset !== offset) {
  13429. pointer.offset = offset;
  13430. changed = true;
  13431. }
  13432. }
  13433. if (changed || this._vaoRecordInProgress) {
  13434. this.bindArrayBuffer(buffer);
  13435. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13436. }
  13437. };
  13438. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13439. if (indexBuffer == null) {
  13440. return;
  13441. }
  13442. if (this._cachedIndexBuffer !== indexBuffer) {
  13443. this._cachedIndexBuffer = indexBuffer;
  13444. this.bindIndexBuffer(indexBuffer);
  13445. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13446. }
  13447. };
  13448. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13449. var attributes = effect.getAttributesNames();
  13450. if (!this._vaoRecordInProgress) {
  13451. this._unbindVertexArrayObject();
  13452. }
  13453. this.unbindAllAttributes();
  13454. for (var index = 0; index < attributes.length; index++) {
  13455. var order = effect.getAttributeLocation(index);
  13456. if (order >= 0) {
  13457. var vertexBuffer = vertexBuffers[attributes[index]];
  13458. if (!vertexBuffer) {
  13459. continue;
  13460. }
  13461. this._gl.enableVertexAttribArray(order);
  13462. if (!this._vaoRecordInProgress) {
  13463. this._vertexAttribArraysEnabled[order] = true;
  13464. }
  13465. var buffer = vertexBuffer.getBuffer();
  13466. if (buffer) {
  13467. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13468. if (vertexBuffer.getIsInstanced()) {
  13469. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13470. if (!this._vaoRecordInProgress) {
  13471. this._currentInstanceLocations.push(order);
  13472. this._currentInstanceBuffers.push(buffer);
  13473. }
  13474. }
  13475. }
  13476. }
  13477. }
  13478. };
  13479. /**
  13480. * Records a vertex array object
  13481. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13482. * @param vertexBuffers defines the list of vertex buffers to store
  13483. * @param indexBuffer defines the index buffer to store
  13484. * @param effect defines the effect to store
  13485. * @returns the new vertex array object
  13486. */
  13487. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13488. var vao = this._gl.createVertexArray();
  13489. this._vaoRecordInProgress = true;
  13490. this._gl.bindVertexArray(vao);
  13491. this._mustWipeVertexAttributes = true;
  13492. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13493. this.bindIndexBuffer(indexBuffer);
  13494. this._vaoRecordInProgress = false;
  13495. this._gl.bindVertexArray(null);
  13496. return vao;
  13497. };
  13498. /**
  13499. * Bind a specific vertex array object
  13500. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13501. * @param vertexArrayObject defines the vertex array object to bind
  13502. * @param indexBuffer defines the index buffer to bind
  13503. */
  13504. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13505. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13506. this._cachedVertexArrayObject = vertexArrayObject;
  13507. this._gl.bindVertexArray(vertexArrayObject);
  13508. this._cachedVertexBuffers = null;
  13509. this._cachedIndexBuffer = null;
  13510. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13511. this._mustWipeVertexAttributes = true;
  13512. }
  13513. };
  13514. /**
  13515. * Bind webGl buffers directly to the webGL context
  13516. * @param vertexBuffer defines the vertex buffer to bind
  13517. * @param indexBuffer defines the index buffer to bind
  13518. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13519. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13520. * @param effect defines the effect associated with the vertex buffer
  13521. */
  13522. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13523. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13524. this._cachedVertexBuffers = vertexBuffer;
  13525. this._cachedEffectForVertexBuffers = effect;
  13526. var attributesCount = effect.getAttributesCount();
  13527. this._unbindVertexArrayObject();
  13528. this.unbindAllAttributes();
  13529. var offset = 0;
  13530. for (var index = 0; index < attributesCount; index++) {
  13531. if (index < vertexDeclaration.length) {
  13532. var order = effect.getAttributeLocation(index);
  13533. if (order >= 0) {
  13534. this._gl.enableVertexAttribArray(order);
  13535. this._vertexAttribArraysEnabled[order] = true;
  13536. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13537. }
  13538. offset += vertexDeclaration[index] * 4;
  13539. }
  13540. }
  13541. }
  13542. this._bindIndexBufferWithCache(indexBuffer);
  13543. };
  13544. Engine.prototype._unbindVertexArrayObject = function () {
  13545. if (!this._cachedVertexArrayObject) {
  13546. return;
  13547. }
  13548. this._cachedVertexArrayObject = null;
  13549. this._gl.bindVertexArray(null);
  13550. };
  13551. /**
  13552. * Bind a list of vertex buffers to the webGL context
  13553. * @param vertexBuffers defines the list of vertex buffers to bind
  13554. * @param indexBuffer defines the index buffer to bind
  13555. * @param effect defines the effect associated with the vertex buffers
  13556. */
  13557. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13558. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13559. this._cachedVertexBuffers = vertexBuffers;
  13560. this._cachedEffectForVertexBuffers = effect;
  13561. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13562. }
  13563. this._bindIndexBufferWithCache(indexBuffer);
  13564. };
  13565. /**
  13566. * Unbind all instance attributes
  13567. */
  13568. Engine.prototype.unbindInstanceAttributes = function () {
  13569. var boundBuffer;
  13570. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13571. var instancesBuffer = this._currentInstanceBuffers[i];
  13572. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13573. boundBuffer = instancesBuffer;
  13574. this.bindArrayBuffer(instancesBuffer);
  13575. }
  13576. var offsetLocation = this._currentInstanceLocations[i];
  13577. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13578. }
  13579. this._currentInstanceBuffers.length = 0;
  13580. this._currentInstanceLocations.length = 0;
  13581. };
  13582. /**
  13583. * Release and free the memory of a vertex array object
  13584. * @param vao defines the vertex array object to delete
  13585. */
  13586. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13587. this._gl.deleteVertexArray(vao);
  13588. };
  13589. /** @hidden */
  13590. Engine.prototype._releaseBuffer = function (buffer) {
  13591. buffer.references--;
  13592. if (buffer.references === 0) {
  13593. this._gl.deleteBuffer(buffer);
  13594. return true;
  13595. }
  13596. return false;
  13597. };
  13598. /**
  13599. * Creates a webGL buffer to use with instanciation
  13600. * @param capacity defines the size of the buffer
  13601. * @returns the webGL buffer
  13602. */
  13603. Engine.prototype.createInstancesBuffer = function (capacity) {
  13604. var buffer = this._gl.createBuffer();
  13605. if (!buffer) {
  13606. throw new Error("Unable to create instance buffer");
  13607. }
  13608. buffer.capacity = capacity;
  13609. this.bindArrayBuffer(buffer);
  13610. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13611. return buffer;
  13612. };
  13613. /**
  13614. * Delete a webGL buffer used with instanciation
  13615. * @param buffer defines the webGL buffer to delete
  13616. */
  13617. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13618. this._gl.deleteBuffer(buffer);
  13619. };
  13620. /**
  13621. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13622. * @param instancesBuffer defines the webGL buffer to update and bind
  13623. * @param data defines the data to store in the buffer
  13624. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13625. */
  13626. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13627. this.bindArrayBuffer(instancesBuffer);
  13628. if (data) {
  13629. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13630. }
  13631. if (offsetLocations[0].index !== undefined) {
  13632. var stride = 0;
  13633. for (var i = 0; i < offsetLocations.length; i++) {
  13634. var ai = offsetLocations[i];
  13635. stride += ai.attributeSize * 4;
  13636. }
  13637. for (var i = 0; i < offsetLocations.length; i++) {
  13638. var ai = offsetLocations[i];
  13639. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13640. this._gl.enableVertexAttribArray(ai.index);
  13641. this._vertexAttribArraysEnabled[ai.index] = true;
  13642. }
  13643. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13644. this._gl.vertexAttribDivisor(ai.index, 1);
  13645. this._currentInstanceLocations.push(ai.index);
  13646. this._currentInstanceBuffers.push(instancesBuffer);
  13647. }
  13648. }
  13649. else {
  13650. for (var index = 0; index < 4; index++) {
  13651. var offsetLocation = offsetLocations[index];
  13652. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13653. this._gl.enableVertexAttribArray(offsetLocation);
  13654. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13655. }
  13656. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13657. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13658. this._currentInstanceLocations.push(offsetLocation);
  13659. this._currentInstanceBuffers.push(instancesBuffer);
  13660. }
  13661. }
  13662. };
  13663. /**
  13664. * Apply all cached states (depth, culling, stencil and alpha)
  13665. */
  13666. Engine.prototype.applyStates = function () {
  13667. this._depthCullingState.apply(this._gl);
  13668. this._stencilState.apply(this._gl);
  13669. this._alphaState.apply(this._gl);
  13670. };
  13671. /**
  13672. * Send a draw order
  13673. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13674. * @param indexStart defines the starting index
  13675. * @param indexCount defines the number of index to draw
  13676. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13677. */
  13678. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13679. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13680. };
  13681. /**
  13682. * Draw a list of points
  13683. * @param verticesStart defines the index of first vertex to draw
  13684. * @param verticesCount defines the count of vertices to draw
  13685. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13686. */
  13687. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13688. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13689. };
  13690. /**
  13691. * Draw a list of unindexed primitives
  13692. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13693. * @param verticesStart defines the index of first vertex to draw
  13694. * @param verticesCount defines the count of vertices to draw
  13695. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13696. */
  13697. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13698. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13699. };
  13700. /**
  13701. * Draw a list of indexed primitives
  13702. * @param fillMode defines the primitive to use
  13703. * @param indexStart defines the starting index
  13704. * @param indexCount defines the number of index to draw
  13705. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13706. */
  13707. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13708. // Apply states
  13709. this.applyStates();
  13710. this._drawCalls.addCount(1, false);
  13711. // Render
  13712. var drawMode = this._drawMode(fillMode);
  13713. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13714. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13715. if (instancesCount) {
  13716. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13717. }
  13718. else {
  13719. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13720. }
  13721. };
  13722. /**
  13723. * Draw a list of unindexed primitives
  13724. * @param fillMode defines the primitive to use
  13725. * @param verticesStart defines the index of first vertex to draw
  13726. * @param verticesCount defines the count of vertices to draw
  13727. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13728. */
  13729. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13730. // Apply states
  13731. this.applyStates();
  13732. this._drawCalls.addCount(1, false);
  13733. var drawMode = this._drawMode(fillMode);
  13734. if (instancesCount) {
  13735. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13736. }
  13737. else {
  13738. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13739. }
  13740. };
  13741. Engine.prototype._drawMode = function (fillMode) {
  13742. switch (fillMode) {
  13743. // Triangle views
  13744. case BABYLON.Material.TriangleFillMode:
  13745. return this._gl.TRIANGLES;
  13746. case BABYLON.Material.PointFillMode:
  13747. return this._gl.POINTS;
  13748. case BABYLON.Material.WireFrameFillMode:
  13749. return this._gl.LINES;
  13750. // Draw modes
  13751. case BABYLON.Material.PointListDrawMode:
  13752. return this._gl.POINTS;
  13753. case BABYLON.Material.LineListDrawMode:
  13754. return this._gl.LINES;
  13755. case BABYLON.Material.LineLoopDrawMode:
  13756. return this._gl.LINE_LOOP;
  13757. case BABYLON.Material.LineStripDrawMode:
  13758. return this._gl.LINE_STRIP;
  13759. case BABYLON.Material.TriangleStripDrawMode:
  13760. return this._gl.TRIANGLE_STRIP;
  13761. case BABYLON.Material.TriangleFanDrawMode:
  13762. return this._gl.TRIANGLE_FAN;
  13763. default:
  13764. return this._gl.TRIANGLES;
  13765. }
  13766. };
  13767. // Shaders
  13768. /** @hidden */
  13769. Engine.prototype._releaseEffect = function (effect) {
  13770. if (this._compiledEffects[effect._key]) {
  13771. delete this._compiledEffects[effect._key];
  13772. this._deleteProgram(effect.getProgram());
  13773. }
  13774. };
  13775. /** @hidden */
  13776. Engine.prototype._deleteProgram = function (program) {
  13777. if (program) {
  13778. program.__SPECTOR_rebuildProgram = null;
  13779. if (program.transformFeedback) {
  13780. this.deleteTransformFeedback(program.transformFeedback);
  13781. program.transformFeedback = null;
  13782. }
  13783. this._gl.deleteProgram(program);
  13784. }
  13785. };
  13786. /**
  13787. * Create a new effect (used to store vertex/fragment shaders)
  13788. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13789. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13790. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13791. * @param samplers defines an array of string used to represent textures
  13792. * @param defines defines the string containing the defines to use to compile the shaders
  13793. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13794. * @param onCompiled defines a function to call when the effect creation is successful
  13795. * @param onError defines a function to call when the effect creation has failed
  13796. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13797. * @returns the new Effect
  13798. */
  13799. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13800. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13801. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13802. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13803. if (this._compiledEffects[name]) {
  13804. var compiledEffect = this._compiledEffects[name];
  13805. if (onCompiled && compiledEffect.isReady()) {
  13806. onCompiled(compiledEffect);
  13807. }
  13808. return compiledEffect;
  13809. }
  13810. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13811. effect._key = name;
  13812. this._compiledEffects[name] = effect;
  13813. return effect;
  13814. };
  13815. /**
  13816. * Create an effect to use with particle systems
  13817. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13818. * @param uniformsNames defines a list of attribute names
  13819. * @param samplers defines an array of string used to represent textures
  13820. * @param defines defines the string containing the defines to use to compile the shaders
  13821. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13822. * @param onCompiled defines a function to call when the effect creation is successful
  13823. * @param onError defines a function to call when the effect creation has failed
  13824. * @returns the new Effect
  13825. */
  13826. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13827. if (uniformsNames === void 0) { uniformsNames = []; }
  13828. if (samplers === void 0) { samplers = []; }
  13829. if (defines === void 0) { defines = ""; }
  13830. return this.createEffect({
  13831. vertex: "particles",
  13832. fragmentElement: fragmentName
  13833. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13834. };
  13835. /**
  13836. * Directly creates a webGL program
  13837. * @param vertexCode defines the vertex shader code to use
  13838. * @param fragmentCode defines the fragment shader code to use
  13839. * @param context defines the webGL context to use (if not set, the current one will be used)
  13840. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13841. * @returns the new webGL program
  13842. */
  13843. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13844. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13845. context = context || this._gl;
  13846. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13847. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13848. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13849. };
  13850. /**
  13851. * Creates a webGL program
  13852. * @param vertexCode defines the vertex shader code to use
  13853. * @param fragmentCode defines the fragment shader code to use
  13854. * @param defines defines the string containing the defines to use to compile the shaders
  13855. * @param context defines the webGL context to use (if not set, the current one will be used)
  13856. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13857. * @returns the new webGL program
  13858. */
  13859. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13860. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13861. context = context || this._gl;
  13862. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13863. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13864. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13865. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13866. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13867. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13868. return program;
  13869. };
  13870. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13871. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13872. var shaderProgram = context.createProgram();
  13873. if (!shaderProgram) {
  13874. throw new Error("Unable to create program");
  13875. }
  13876. context.attachShader(shaderProgram, vertexShader);
  13877. context.attachShader(shaderProgram, fragmentShader);
  13878. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13879. var transformFeedback = this.createTransformFeedback();
  13880. this.bindTransformFeedback(transformFeedback);
  13881. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13882. shaderProgram.transformFeedback = transformFeedback;
  13883. }
  13884. context.linkProgram(shaderProgram);
  13885. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13886. this.bindTransformFeedback(null);
  13887. }
  13888. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13889. if (!linked) {
  13890. context.validateProgram(shaderProgram);
  13891. var error = context.getProgramInfoLog(shaderProgram);
  13892. if (error) {
  13893. throw new Error(error);
  13894. }
  13895. }
  13896. context.deleteShader(vertexShader);
  13897. context.deleteShader(fragmentShader);
  13898. return shaderProgram;
  13899. };
  13900. /**
  13901. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13902. * @param shaderProgram defines the webGL program to use
  13903. * @param uniformsNames defines the list of uniform names
  13904. * @returns an array of webGL uniform locations
  13905. */
  13906. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13907. var results = new Array();
  13908. for (var index = 0; index < uniformsNames.length; index++) {
  13909. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13910. }
  13911. return results;
  13912. };
  13913. /**
  13914. * Gets the lsit of active attributes for a given webGL program
  13915. * @param shaderProgram defines the webGL program to use
  13916. * @param attributesNames defines the list of attribute names to get
  13917. * @returns an array of indices indicating the offset of each attribute
  13918. */
  13919. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13920. var results = [];
  13921. for (var index = 0; index < attributesNames.length; index++) {
  13922. try {
  13923. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13924. }
  13925. catch (e) {
  13926. results.push(-1);
  13927. }
  13928. }
  13929. return results;
  13930. };
  13931. /**
  13932. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13933. * @param effect defines the effect to activate
  13934. */
  13935. Engine.prototype.enableEffect = function (effect) {
  13936. if (!effect) {
  13937. return;
  13938. }
  13939. // Use program
  13940. this.bindSamplers(effect);
  13941. this._currentEffect = effect;
  13942. if (effect.onBind) {
  13943. effect.onBind(effect);
  13944. }
  13945. effect.onBindObservable.notifyObservers(effect);
  13946. };
  13947. /**
  13948. * Set the value of an uniform to an array of int32
  13949. * @param uniform defines the webGL uniform location where to store the value
  13950. * @param array defines the array of int32 to store
  13951. */
  13952. Engine.prototype.setIntArray = function (uniform, array) {
  13953. if (!uniform)
  13954. return;
  13955. this._gl.uniform1iv(uniform, array);
  13956. };
  13957. /**
  13958. * Set the value of an uniform to an array of int32 (stored as vec2)
  13959. * @param uniform defines the webGL uniform location where to store the value
  13960. * @param array defines the array of int32 to store
  13961. */
  13962. Engine.prototype.setIntArray2 = function (uniform, array) {
  13963. if (!uniform || array.length % 2 !== 0)
  13964. return;
  13965. this._gl.uniform2iv(uniform, array);
  13966. };
  13967. /**
  13968. * Set the value of an uniform to an array of int32 (stored as vec3)
  13969. * @param uniform defines the webGL uniform location where to store the value
  13970. * @param array defines the array of int32 to store
  13971. */
  13972. Engine.prototype.setIntArray3 = function (uniform, array) {
  13973. if (!uniform || array.length % 3 !== 0)
  13974. return;
  13975. this._gl.uniform3iv(uniform, array);
  13976. };
  13977. /**
  13978. * Set the value of an uniform to an array of int32 (stored as vec4)
  13979. * @param uniform defines the webGL uniform location where to store the value
  13980. * @param array defines the array of int32 to store
  13981. */
  13982. Engine.prototype.setIntArray4 = function (uniform, array) {
  13983. if (!uniform || array.length % 4 !== 0)
  13984. return;
  13985. this._gl.uniform4iv(uniform, array);
  13986. };
  13987. /**
  13988. * Set the value of an uniform to an array of float32
  13989. * @param uniform defines the webGL uniform location where to store the value
  13990. * @param array defines the array of float32 to store
  13991. */
  13992. Engine.prototype.setFloatArray = function (uniform, array) {
  13993. if (!uniform)
  13994. return;
  13995. this._gl.uniform1fv(uniform, array);
  13996. };
  13997. /**
  13998. * Set the value of an uniform to an array of float32 (stored as vec2)
  13999. * @param uniform defines the webGL uniform location where to store the value
  14000. * @param array defines the array of float32 to store
  14001. */
  14002. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14003. if (!uniform || array.length % 2 !== 0)
  14004. return;
  14005. this._gl.uniform2fv(uniform, array);
  14006. };
  14007. /**
  14008. * Set the value of an uniform to an array of float32 (stored as vec3)
  14009. * @param uniform defines the webGL uniform location where to store the value
  14010. * @param array defines the array of float32 to store
  14011. */
  14012. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14013. if (!uniform || array.length % 3 !== 0)
  14014. return;
  14015. this._gl.uniform3fv(uniform, array);
  14016. };
  14017. /**
  14018. * Set the value of an uniform to an array of float32 (stored as vec4)
  14019. * @param uniform defines the webGL uniform location where to store the value
  14020. * @param array defines the array of float32 to store
  14021. */
  14022. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14023. if (!uniform || array.length % 4 !== 0)
  14024. return;
  14025. this._gl.uniform4fv(uniform, array);
  14026. };
  14027. /**
  14028. * Set the value of an uniform to an array of number
  14029. * @param uniform defines the webGL uniform location where to store the value
  14030. * @param array defines the array of number to store
  14031. */
  14032. Engine.prototype.setArray = function (uniform, array) {
  14033. if (!uniform)
  14034. return;
  14035. this._gl.uniform1fv(uniform, array);
  14036. };
  14037. /**
  14038. * Set the value of an uniform to an array of number (stored as vec2)
  14039. * @param uniform defines the webGL uniform location where to store the value
  14040. * @param array defines the array of number to store
  14041. */
  14042. Engine.prototype.setArray2 = function (uniform, array) {
  14043. if (!uniform || array.length % 2 !== 0)
  14044. return;
  14045. this._gl.uniform2fv(uniform, array);
  14046. };
  14047. /**
  14048. * Set the value of an uniform to an array of number (stored as vec3)
  14049. * @param uniform defines the webGL uniform location where to store the value
  14050. * @param array defines the array of number to store
  14051. */
  14052. Engine.prototype.setArray3 = function (uniform, array) {
  14053. if (!uniform || array.length % 3 !== 0)
  14054. return;
  14055. this._gl.uniform3fv(uniform, array);
  14056. };
  14057. /**
  14058. * Set the value of an uniform to an array of number (stored as vec4)
  14059. * @param uniform defines the webGL uniform location where to store the value
  14060. * @param array defines the array of number to store
  14061. */
  14062. Engine.prototype.setArray4 = function (uniform, array) {
  14063. if (!uniform || array.length % 4 !== 0)
  14064. return;
  14065. this._gl.uniform4fv(uniform, array);
  14066. };
  14067. /**
  14068. * Set the value of an uniform to an array of float32 (stored as matrices)
  14069. * @param uniform defines the webGL uniform location where to store the value
  14070. * @param matrices defines the array of float32 to store
  14071. */
  14072. Engine.prototype.setMatrices = function (uniform, matrices) {
  14073. if (!uniform)
  14074. return;
  14075. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14076. };
  14077. /**
  14078. * Set the value of an uniform to a matrix
  14079. * @param uniform defines the webGL uniform location where to store the value
  14080. * @param matrix defines the matrix to store
  14081. */
  14082. Engine.prototype.setMatrix = function (uniform, matrix) {
  14083. if (!uniform)
  14084. return;
  14085. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14086. };
  14087. /**
  14088. * Set the value of an uniform to a matrix (3x3)
  14089. * @param uniform defines the webGL uniform location where to store the value
  14090. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14091. */
  14092. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14093. if (!uniform)
  14094. return;
  14095. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14096. };
  14097. /**
  14098. * Set the value of an uniform to a matrix (2x2)
  14099. * @param uniform defines the webGL uniform location where to store the value
  14100. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14101. */
  14102. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14103. if (!uniform)
  14104. return;
  14105. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14106. };
  14107. /**
  14108. * Set the value of an uniform to a number (int)
  14109. * @param uniform defines the webGL uniform location where to store the value
  14110. * @param value defines the int number to store
  14111. */
  14112. Engine.prototype.setInt = function (uniform, value) {
  14113. if (!uniform)
  14114. return;
  14115. this._gl.uniform1i(uniform, value);
  14116. };
  14117. /**
  14118. * Set the value of an uniform to a number (float)
  14119. * @param uniform defines the webGL uniform location where to store the value
  14120. * @param value defines the float number to store
  14121. */
  14122. Engine.prototype.setFloat = function (uniform, value) {
  14123. if (!uniform)
  14124. return;
  14125. this._gl.uniform1f(uniform, value);
  14126. };
  14127. /**
  14128. * Set the value of an uniform to a vec2
  14129. * @param uniform defines the webGL uniform location where to store the value
  14130. * @param x defines the 1st component of the value
  14131. * @param y defines the 2nd component of the value
  14132. */
  14133. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniform2f(uniform, x, y);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to a vec3
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param x defines the 1st component of the value
  14142. * @param y defines the 2nd component of the value
  14143. * @param z defines the 3rd component of the value
  14144. */
  14145. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14146. if (!uniform)
  14147. return;
  14148. this._gl.uniform3f(uniform, x, y, z);
  14149. };
  14150. /**
  14151. * Set the value of an uniform to a boolean
  14152. * @param uniform defines the webGL uniform location where to store the value
  14153. * @param bool defines the boolean to store
  14154. */
  14155. Engine.prototype.setBool = function (uniform, bool) {
  14156. if (!uniform)
  14157. return;
  14158. this._gl.uniform1i(uniform, bool);
  14159. };
  14160. /**
  14161. * Set the value of an uniform to a vec4
  14162. * @param uniform defines the webGL uniform location where to store the value
  14163. * @param x defines the 1st component of the value
  14164. * @param y defines the 2nd component of the value
  14165. * @param z defines the 3rd component of the value
  14166. * @param w defines the 4th component of the value
  14167. */
  14168. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14169. if (!uniform)
  14170. return;
  14171. this._gl.uniform4f(uniform, x, y, z, w);
  14172. };
  14173. /**
  14174. * Set the value of an uniform to a Color3
  14175. * @param uniform defines the webGL uniform location where to store the value
  14176. * @param color3 defines the color to store
  14177. */
  14178. Engine.prototype.setColor3 = function (uniform, color3) {
  14179. if (!uniform)
  14180. return;
  14181. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14182. };
  14183. /**
  14184. * Set the value of an uniform to a Color3 and an alpha value
  14185. * @param uniform defines the webGL uniform location where to store the value
  14186. * @param color3 defines the color to store
  14187. * @param alpha defines the alpha component to store
  14188. */
  14189. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14190. if (!uniform)
  14191. return;
  14192. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14193. };
  14194. /**
  14195. * Sets a Color4 on a uniform variable
  14196. * @param uniform defines the uniform location
  14197. * @param color4 defines the value to be set
  14198. */
  14199. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14200. if (!uniform)
  14201. return;
  14202. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14203. };
  14204. // States
  14205. /**
  14206. * Set various states to the webGL context
  14207. * @param culling defines backface culling state
  14208. * @param zOffset defines the value to apply to zOffset (0 by default)
  14209. * @param force defines if states must be applied even if cache is up to date
  14210. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14211. */
  14212. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14213. if (zOffset === void 0) { zOffset = 0; }
  14214. if (reverseSide === void 0) { reverseSide = false; }
  14215. // Culling
  14216. if (this._depthCullingState.cull !== culling || force) {
  14217. this._depthCullingState.cull = culling;
  14218. }
  14219. // Cull face
  14220. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14221. if (this._depthCullingState.cullFace !== cullFace || force) {
  14222. this._depthCullingState.cullFace = cullFace;
  14223. }
  14224. // Z offset
  14225. this.setZOffset(zOffset);
  14226. // Front face
  14227. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14228. if (this._depthCullingState.frontFace !== frontFace || force) {
  14229. this._depthCullingState.frontFace = frontFace;
  14230. }
  14231. };
  14232. /**
  14233. * Set the z offset to apply to current rendering
  14234. * @param value defines the offset to apply
  14235. */
  14236. Engine.prototype.setZOffset = function (value) {
  14237. this._depthCullingState.zOffset = value;
  14238. };
  14239. /**
  14240. * Gets the current value of the zOffset
  14241. * @returns the current zOffset state
  14242. */
  14243. Engine.prototype.getZOffset = function () {
  14244. return this._depthCullingState.zOffset;
  14245. };
  14246. /**
  14247. * Enable or disable depth buffering
  14248. * @param enable defines the state to set
  14249. */
  14250. Engine.prototype.setDepthBuffer = function (enable) {
  14251. this._depthCullingState.depthTest = enable;
  14252. };
  14253. /**
  14254. * Gets a boolean indicating if depth writing is enabled
  14255. * @returns the current depth writing state
  14256. */
  14257. Engine.prototype.getDepthWrite = function () {
  14258. return this._depthCullingState.depthMask;
  14259. };
  14260. /**
  14261. * Enable or disable depth writing
  14262. * @param enable defines the state to set
  14263. */
  14264. Engine.prototype.setDepthWrite = function (enable) {
  14265. this._depthCullingState.depthMask = enable;
  14266. };
  14267. /**
  14268. * Enable or disable color writing
  14269. * @param enable defines the state to set
  14270. */
  14271. Engine.prototype.setColorWrite = function (enable) {
  14272. this._gl.colorMask(enable, enable, enable, enable);
  14273. this._colorWrite = enable;
  14274. };
  14275. /**
  14276. * Gets a boolean indicating if color writing is enabled
  14277. * @returns the current color writing state
  14278. */
  14279. Engine.prototype.getColorWrite = function () {
  14280. return this._colorWrite;
  14281. };
  14282. /**
  14283. * Sets alpha constants used by some alpha blending modes
  14284. * @param r defines the red component
  14285. * @param g defines the green component
  14286. * @param b defines the blue component
  14287. * @param a defines the alpha component
  14288. */
  14289. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14290. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14291. };
  14292. /**
  14293. * Sets the current alpha mode
  14294. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14295. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14296. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14297. */
  14298. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14299. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14300. if (this._alphaMode === mode) {
  14301. return;
  14302. }
  14303. switch (mode) {
  14304. case Engine.ALPHA_DISABLE:
  14305. this._alphaState.alphaBlend = false;
  14306. break;
  14307. case Engine.ALPHA_PREMULTIPLIED:
  14308. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14309. this._alphaState.alphaBlend = true;
  14310. break;
  14311. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14312. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14313. this._alphaState.alphaBlend = true;
  14314. break;
  14315. case Engine.ALPHA_COMBINE:
  14316. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14317. this._alphaState.alphaBlend = true;
  14318. break;
  14319. case Engine.ALPHA_ONEONE:
  14320. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14321. this._alphaState.alphaBlend = true;
  14322. break;
  14323. case Engine.ALPHA_ADD:
  14324. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14325. this._alphaState.alphaBlend = true;
  14326. break;
  14327. case Engine.ALPHA_SUBTRACT:
  14328. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14329. this._alphaState.alphaBlend = true;
  14330. break;
  14331. case Engine.ALPHA_MULTIPLY:
  14332. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14333. this._alphaState.alphaBlend = true;
  14334. break;
  14335. case Engine.ALPHA_MAXIMIZED:
  14336. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14337. this._alphaState.alphaBlend = true;
  14338. break;
  14339. case Engine.ALPHA_INTERPOLATE:
  14340. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14341. this._alphaState.alphaBlend = true;
  14342. break;
  14343. case Engine.ALPHA_SCREENMODE:
  14344. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14345. this._alphaState.alphaBlend = true;
  14346. break;
  14347. }
  14348. if (!noDepthWriteChange) {
  14349. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14350. }
  14351. this._alphaMode = mode;
  14352. };
  14353. /**
  14354. * Gets the current alpha mode
  14355. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14356. * @returns the current alpha mode
  14357. */
  14358. Engine.prototype.getAlphaMode = function () {
  14359. return this._alphaMode;
  14360. };
  14361. // Textures
  14362. /**
  14363. * Force the entire cache to be cleared
  14364. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14365. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14366. */
  14367. Engine.prototype.wipeCaches = function (bruteForce) {
  14368. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14369. return;
  14370. }
  14371. this._currentEffect = null;
  14372. if (bruteForce) {
  14373. this.resetTextureCache();
  14374. this._currentProgram = null;
  14375. this._stencilState.reset();
  14376. this._depthCullingState.reset();
  14377. this.setDepthFunctionToLessOrEqual();
  14378. this._alphaState.reset();
  14379. }
  14380. this._resetVertexBufferBinding();
  14381. this._cachedIndexBuffer = null;
  14382. this._cachedEffectForVertexBuffers = null;
  14383. this._unbindVertexArrayObject();
  14384. this.bindIndexBuffer(null);
  14385. };
  14386. /**
  14387. * Set the compressed texture format to use, based on the formats you have, and the formats
  14388. * supported by the hardware / browser.
  14389. *
  14390. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14391. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14392. * to API arguments needed to compressed textures. This puts the burden on the container
  14393. * generator to house the arcane code for determining these for current & future formats.
  14394. *
  14395. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14396. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14397. *
  14398. * Note: The result of this call is not taken into account when a texture is base64.
  14399. *
  14400. * @param formatsAvailable defines the list of those format families you have created
  14401. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14402. *
  14403. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14404. * @returns The extension selected.
  14405. */
  14406. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14407. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14408. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14409. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14410. return this._textureFormatInUse = this._texturesSupported[i];
  14411. }
  14412. }
  14413. }
  14414. // actively set format to nothing, to allow this to be called more than once
  14415. // and possibly fail the 2nd time
  14416. this._textureFormatInUse = null;
  14417. return null;
  14418. };
  14419. /** @hidden */
  14420. Engine.prototype._createTexture = function () {
  14421. var texture = this._gl.createTexture();
  14422. if (!texture) {
  14423. throw new Error("Unable to create texture");
  14424. }
  14425. return texture;
  14426. };
  14427. /**
  14428. * Usually called from BABYLON.Texture.ts.
  14429. * Passed information to create a WebGLTexture
  14430. * @param urlArg defines a value which contains one of the following:
  14431. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14432. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14433. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14434. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14435. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14436. * @param scene needed for loading to the correct scene
  14437. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14438. * @param onLoad optional callback to be called upon successful completion
  14439. * @param onError optional callback to be called upon failure
  14440. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14441. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14442. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14443. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14444. */
  14445. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14446. var _this = this;
  14447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14448. if (onLoad === void 0) { onLoad = null; }
  14449. if (onError === void 0) { onError = null; }
  14450. if (buffer === void 0) { buffer = null; }
  14451. if (fallback === void 0) { fallback = null; }
  14452. if (format === void 0) { format = null; }
  14453. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14454. var fromData = url.substr(0, 5) === "data:";
  14455. var fromBlob = url.substr(0, 5) === "blob:";
  14456. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14457. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14458. // establish the file extension, if possible
  14459. var lastDot = url.lastIndexOf('.');
  14460. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14461. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14462. var isTGA = (extension.indexOf(".tga") === 0);
  14463. // determine if a ktx file should be substituted
  14464. var isKTX = false;
  14465. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14466. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14467. isKTX = true;
  14468. }
  14469. if (scene) {
  14470. scene._addPendingData(texture);
  14471. }
  14472. texture.url = url;
  14473. texture.generateMipMaps = !noMipmap;
  14474. texture.samplingMode = samplingMode;
  14475. texture.invertY = invertY;
  14476. if (!this._doNotHandleContextLost) {
  14477. // Keep a link to the buffer only if we plan to handle context lost
  14478. texture._buffer = buffer;
  14479. }
  14480. var onLoadObserver = null;
  14481. if (onLoad && !fallback) {
  14482. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14483. }
  14484. if (!fallback)
  14485. this._internalTexturesCache.push(texture);
  14486. var onerror = function (message, exception) {
  14487. if (scene) {
  14488. scene._removePendingData(texture);
  14489. }
  14490. if (onLoadObserver) {
  14491. texture.onLoadedObservable.remove(onLoadObserver);
  14492. }
  14493. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14494. if (isKTX) {
  14495. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14496. }
  14497. else if (BABYLON.Tools.UseFallbackTexture) {
  14498. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14499. }
  14500. if (onError) {
  14501. onError(message || "Unknown error", exception);
  14502. }
  14503. };
  14504. var callback = null;
  14505. // processing for non-image formats
  14506. if (isKTX || isTGA || isDDS) {
  14507. if (isKTX) {
  14508. callback = function (data) {
  14509. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14510. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14511. ktx.uploadLevels(_this._gl, !noMipmap);
  14512. return false;
  14513. }, samplingMode);
  14514. };
  14515. }
  14516. else if (isTGA) {
  14517. callback = function (arrayBuffer) {
  14518. var data = new Uint8Array(arrayBuffer);
  14519. var header = BABYLON.TGATools.GetTGAHeader(data);
  14520. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14521. BABYLON.TGATools.UploadContent(_this._gl, data);
  14522. return false;
  14523. }, samplingMode);
  14524. };
  14525. }
  14526. else if (isDDS) {
  14527. callback = function (data) {
  14528. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14529. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14530. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14531. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14532. return false;
  14533. }, samplingMode);
  14534. };
  14535. }
  14536. if (!buffer) {
  14537. this._loadFile(url, function (data) {
  14538. if (callback) {
  14539. callback(data);
  14540. }
  14541. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14542. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14543. });
  14544. }
  14545. else {
  14546. if (callback) {
  14547. callback(buffer);
  14548. }
  14549. }
  14550. // image format processing
  14551. }
  14552. else {
  14553. var onload = function (img) {
  14554. if (fromBlob && !_this._doNotHandleContextLost) {
  14555. // We need to store the image if we need to rebuild the texture
  14556. // in case of a webgl context lost
  14557. texture._buffer = img;
  14558. }
  14559. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14560. var gl = _this._gl;
  14561. var isPot = (img.width === potWidth && img.height === potHeight);
  14562. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14563. if (isPot) {
  14564. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14565. return false;
  14566. }
  14567. // Using shaders to rescale because canvas.drawImage is lossy
  14568. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14569. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14570. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14571. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14575. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14576. _this._releaseTexture(source);
  14577. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14578. continuationCallback();
  14579. });
  14580. return true;
  14581. }, samplingMode);
  14582. };
  14583. if (!fromData || isBase64)
  14584. if (buffer instanceof HTMLImageElement) {
  14585. onload(buffer);
  14586. }
  14587. else {
  14588. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14589. }
  14590. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14591. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14592. else
  14593. onload(buffer);
  14594. }
  14595. return texture;
  14596. };
  14597. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14598. var _this = this;
  14599. var rtt = this.createRenderTargetTexture({
  14600. width: destination.width,
  14601. height: destination.height,
  14602. }, {
  14603. generateMipMaps: false,
  14604. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14605. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14606. generateDepthBuffer: false,
  14607. generateStencilBuffer: false
  14608. });
  14609. if (!this._rescalePostProcess) {
  14610. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14611. }
  14612. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14613. _this._rescalePostProcess.onApply = function (effect) {
  14614. effect._bindTexture("textureSampler", source);
  14615. };
  14616. var hostingScene = scene;
  14617. if (!hostingScene) {
  14618. hostingScene = _this.scenes[_this.scenes.length - 1];
  14619. }
  14620. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14621. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14622. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14623. _this.unBindFramebuffer(rtt);
  14624. _this._releaseTexture(rtt);
  14625. if (onComplete) {
  14626. onComplete();
  14627. }
  14628. });
  14629. };
  14630. /**
  14631. * Update a raw texture
  14632. * @param texture defines the texture to update
  14633. * @param data defines the data to store in the texture
  14634. * @param format defines the format of the data
  14635. * @param invertY defines if data must be stored with Y axis inverted
  14636. * @param compression defines the compression used (null by default)
  14637. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14638. */
  14639. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14640. if (compression === void 0) { compression = null; }
  14641. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14642. if (!texture) {
  14643. return;
  14644. }
  14645. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14646. var internalFormat = this._getInternalFormat(format);
  14647. var textureType = this._getWebGLTextureType(type);
  14648. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14649. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14650. if (!this._doNotHandleContextLost) {
  14651. texture._bufferView = data;
  14652. texture.format = format;
  14653. texture.type = type;
  14654. texture.invertY = invertY;
  14655. texture._compression = compression;
  14656. }
  14657. if (texture.width % 4 !== 0) {
  14658. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14659. }
  14660. if (compression && data) {
  14661. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14662. }
  14663. else {
  14664. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14665. }
  14666. if (texture.generateMipMaps) {
  14667. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14668. }
  14669. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14670. // this.resetTextureCache();
  14671. texture.isReady = true;
  14672. };
  14673. /**
  14674. * Creates a raw texture
  14675. * @param data defines the data to store in the texture
  14676. * @param width defines the width of the texture
  14677. * @param height defines the height of the texture
  14678. * @param format defines the format of the data
  14679. * @param generateMipMaps defines if the engine should generate the mip levels
  14680. * @param invertY defines if data must be stored with Y axis inverted
  14681. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14682. * @param compression defines the compression used (null by default)
  14683. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14684. * @returns the raw texture inside an InternalTexture
  14685. */
  14686. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14687. if (compression === void 0) { compression = null; }
  14688. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14689. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14690. texture.baseWidth = width;
  14691. texture.baseHeight = height;
  14692. texture.width = width;
  14693. texture.height = height;
  14694. texture.format = format;
  14695. texture.generateMipMaps = generateMipMaps;
  14696. texture.samplingMode = samplingMode;
  14697. texture.invertY = invertY;
  14698. texture._compression = compression;
  14699. texture.type = type;
  14700. if (!this._doNotHandleContextLost) {
  14701. texture._bufferView = data;
  14702. }
  14703. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14704. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14705. // Filters
  14706. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14707. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14709. if (generateMipMaps) {
  14710. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14711. }
  14712. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14713. this._internalTexturesCache.push(texture);
  14714. return texture;
  14715. };
  14716. /**
  14717. * Creates a dynamic texture
  14718. * @param width defines the width of the texture
  14719. * @param height defines the height of the texture
  14720. * @param generateMipMaps defines if the engine should generate the mip levels
  14721. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14722. * @returns the dynamic texture inside an InternalTexture
  14723. */
  14724. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14726. texture.baseWidth = width;
  14727. texture.baseHeight = height;
  14728. if (generateMipMaps) {
  14729. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14730. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14731. }
  14732. // this.resetTextureCache();
  14733. texture.width = width;
  14734. texture.height = height;
  14735. texture.isReady = false;
  14736. texture.generateMipMaps = generateMipMaps;
  14737. texture.samplingMode = samplingMode;
  14738. this.updateTextureSamplingMode(samplingMode, texture);
  14739. this._internalTexturesCache.push(texture);
  14740. return texture;
  14741. };
  14742. /**
  14743. * Update the sampling mode of a given texture
  14744. * @param samplingMode defines the required sampling mode
  14745. * @param texture defines the texture to update
  14746. */
  14747. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14748. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14749. if (texture.isCube) {
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14751. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14752. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14753. }
  14754. else if (texture.is3D) {
  14755. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14756. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14757. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14758. }
  14759. else {
  14760. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14762. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14763. }
  14764. texture.samplingMode = samplingMode;
  14765. };
  14766. /**
  14767. * Update the content of a dynamic texture
  14768. * @param texture defines the texture to update
  14769. * @param canvas defines the canvas containing the source
  14770. * @param invertY defines if data must be stored with Y axis inverted
  14771. * @param premulAlpha defines if alpha is stored as premultiplied
  14772. * @param format defines the format of the data
  14773. */
  14774. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14775. if (premulAlpha === void 0) { premulAlpha = false; }
  14776. if (!texture) {
  14777. return;
  14778. }
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14780. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14781. if (premulAlpha) {
  14782. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14783. }
  14784. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14785. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14786. if (texture.generateMipMaps) {
  14787. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14788. }
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14790. if (premulAlpha) {
  14791. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14792. }
  14793. texture.isReady = true;
  14794. };
  14795. /**
  14796. * Update a video texture
  14797. * @param texture defines the texture to update
  14798. * @param video defines the video element to use
  14799. * @param invertY defines if data must be stored with Y axis inverted
  14800. */
  14801. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14802. if (!texture || texture._isDisabled) {
  14803. return;
  14804. }
  14805. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14806. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14807. try {
  14808. // Testing video texture support
  14809. if (this._videoTextureSupported === undefined) {
  14810. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14811. if (this._gl.getError() !== 0) {
  14812. this._videoTextureSupported = false;
  14813. }
  14814. else {
  14815. this._videoTextureSupported = true;
  14816. }
  14817. }
  14818. // Copy video through the current working canvas if video texture is not supported
  14819. if (!this._videoTextureSupported) {
  14820. if (!texture._workingCanvas) {
  14821. texture._workingCanvas = document.createElement("canvas");
  14822. var context = texture._workingCanvas.getContext("2d");
  14823. if (!context) {
  14824. throw new Error("Unable to get 2d context");
  14825. }
  14826. texture._workingContext = context;
  14827. texture._workingCanvas.width = texture.width;
  14828. texture._workingCanvas.height = texture.height;
  14829. }
  14830. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14831. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14832. }
  14833. else {
  14834. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14835. }
  14836. if (texture.generateMipMaps) {
  14837. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14838. }
  14839. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14840. // this.resetTextureCache();
  14841. texture.isReady = true;
  14842. }
  14843. catch (ex) {
  14844. // Something unexpected
  14845. // Let's disable the texture
  14846. texture._isDisabled = true;
  14847. }
  14848. };
  14849. /**
  14850. * Updates a depth texture Comparison Mode and Function.
  14851. * If the comparison Function is equal to 0, the mode will be set to none.
  14852. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14853. * @param texture The texture to set the comparison function for
  14854. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14855. */
  14856. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14857. if (this.webGLVersion === 1) {
  14858. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14859. return;
  14860. }
  14861. var gl = this._gl;
  14862. if (texture.isCube) {
  14863. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14864. if (comparisonFunction === 0) {
  14865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14867. }
  14868. else {
  14869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14871. }
  14872. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14873. }
  14874. else {
  14875. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14876. if (comparisonFunction === 0) {
  14877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14879. }
  14880. else {
  14881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14883. }
  14884. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14885. }
  14886. texture._comparisonFunction = comparisonFunction;
  14887. };
  14888. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14889. var width = size.width || size;
  14890. var height = size.height || size;
  14891. internalTexture.baseWidth = width;
  14892. internalTexture.baseHeight = height;
  14893. internalTexture.width = width;
  14894. internalTexture.height = height;
  14895. internalTexture.isReady = true;
  14896. internalTexture.samples = 1;
  14897. internalTexture.generateMipMaps = false;
  14898. internalTexture._generateDepthBuffer = true;
  14899. internalTexture._generateStencilBuffer = generateStencil;
  14900. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14901. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14902. internalTexture._comparisonFunction = comparisonFunction;
  14903. var gl = this._gl;
  14904. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14905. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14906. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14907. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14908. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14909. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14910. if (comparisonFunction === 0) {
  14911. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14912. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14913. }
  14914. else {
  14915. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14916. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14917. }
  14918. };
  14919. /**
  14920. * Creates a depth stencil texture.
  14921. * This is only available in WebGL 2 or with the depth texture extension available.
  14922. * @param size The size of face edge in the texture.
  14923. * @param options The options defining the texture.
  14924. * @returns The texture
  14925. */
  14926. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14927. if (options.isCube) {
  14928. var width = size.width || size;
  14929. return this._createDepthStencilCubeTexture(width, options);
  14930. }
  14931. else {
  14932. return this._createDepthStencilTexture(size, options);
  14933. }
  14934. };
  14935. /**
  14936. * Creates a depth stencil texture.
  14937. * This is only available in WebGL 2 or with the depth texture extension available.
  14938. * @param size The size of face edge in the texture.
  14939. * @param options The options defining the texture.
  14940. * @returns The texture
  14941. */
  14942. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14943. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14944. if (!this._caps.depthTextureExtension) {
  14945. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14946. return internalTexture;
  14947. }
  14948. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14949. var gl = this._gl;
  14950. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14951. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14952. if (this.webGLVersion > 1) {
  14953. if (internalOptions.generateStencil) {
  14954. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14955. }
  14956. else {
  14957. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14958. }
  14959. }
  14960. else {
  14961. if (internalOptions.generateStencil) {
  14962. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14963. }
  14964. else {
  14965. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14966. }
  14967. }
  14968. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14969. return internalTexture;
  14970. };
  14971. /**
  14972. * Creates a depth stencil cube texture.
  14973. * This is only available in WebGL 2.
  14974. * @param size The size of face edge in the cube texture.
  14975. * @param options The options defining the cube texture.
  14976. * @returns The cube texture
  14977. */
  14978. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14979. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14980. internalTexture.isCube = true;
  14981. if (this.webGLVersion === 1) {
  14982. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14983. return internalTexture;
  14984. }
  14985. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14986. var gl = this._gl;
  14987. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14988. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14989. // Create the depth/stencil buffer
  14990. for (var face = 0; face < 6; face++) {
  14991. if (internalOptions.generateStencil) {
  14992. 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);
  14993. }
  14994. else {
  14995. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14996. }
  14997. }
  14998. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14999. return internalTexture;
  15000. };
  15001. /**
  15002. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15003. * @param renderTarget The render target to set the frame buffer for
  15004. */
  15005. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15006. // Create the framebuffer
  15007. var internalTexture = renderTarget.getInternalTexture();
  15008. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15009. return;
  15010. }
  15011. var gl = this._gl;
  15012. var depthStencilTexture = renderTarget.depthStencilTexture;
  15013. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15014. if (depthStencilTexture.isCube) {
  15015. if (depthStencilTexture._generateStencilBuffer) {
  15016. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15017. }
  15018. else {
  15019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15020. }
  15021. }
  15022. else {
  15023. if (depthStencilTexture._generateStencilBuffer) {
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15025. }
  15026. else {
  15027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15028. }
  15029. }
  15030. this.bindUnboundFramebuffer(null);
  15031. };
  15032. /**
  15033. * Creates a new render target texture
  15034. * @param size defines the size of the texture
  15035. * @param options defines the options used to create the texture
  15036. * @returns a new render target texture stored in an InternalTexture
  15037. */
  15038. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15039. var fullOptions = new RenderTargetCreationOptions();
  15040. if (options !== undefined && typeof options === "object") {
  15041. fullOptions.generateMipMaps = options.generateMipMaps;
  15042. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15043. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15044. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15045. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15046. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15047. }
  15048. else {
  15049. fullOptions.generateMipMaps = options;
  15050. fullOptions.generateDepthBuffer = true;
  15051. fullOptions.generateStencilBuffer = false;
  15052. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15053. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15054. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15055. }
  15056. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15057. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15058. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15059. }
  15060. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15061. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15062. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15063. }
  15064. var gl = this._gl;
  15065. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15066. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15067. var width = size.width || size;
  15068. var height = size.height || size;
  15069. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15070. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15071. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15072. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15073. }
  15074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15078. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15079. // Create the framebuffer
  15080. var framebuffer = gl.createFramebuffer();
  15081. this.bindUnboundFramebuffer(framebuffer);
  15082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15083. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15084. if (fullOptions.generateMipMaps) {
  15085. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15086. }
  15087. // Unbind
  15088. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15089. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15090. this.bindUnboundFramebuffer(null);
  15091. texture._framebuffer = framebuffer;
  15092. texture.baseWidth = width;
  15093. texture.baseHeight = height;
  15094. texture.width = width;
  15095. texture.height = height;
  15096. texture.isReady = true;
  15097. texture.samples = 1;
  15098. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15099. texture.samplingMode = fullOptions.samplingMode;
  15100. texture.type = fullOptions.type;
  15101. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15102. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15103. // this.resetTextureCache();
  15104. this._internalTexturesCache.push(texture);
  15105. return texture;
  15106. };
  15107. /**
  15108. * Create a multi render target texture
  15109. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15110. * @param size defines the size of the texture
  15111. * @param options defines the creation options
  15112. * @returns the cube texture as an InternalTexture
  15113. */
  15114. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15115. var generateMipMaps = false;
  15116. var generateDepthBuffer = true;
  15117. var generateStencilBuffer = false;
  15118. var generateDepthTexture = false;
  15119. var textureCount = 1;
  15120. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15121. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15122. var types = new Array();
  15123. var samplingModes = new Array();
  15124. if (options !== undefined) {
  15125. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15126. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15127. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15128. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15129. textureCount = options.textureCount || 1;
  15130. if (options.types) {
  15131. types = options.types;
  15132. }
  15133. if (options.samplingModes) {
  15134. samplingModes = options.samplingModes;
  15135. }
  15136. }
  15137. var gl = this._gl;
  15138. // Create the framebuffer
  15139. var framebuffer = gl.createFramebuffer();
  15140. this.bindUnboundFramebuffer(framebuffer);
  15141. var width = size.width || size;
  15142. var height = size.height || size;
  15143. var textures = [];
  15144. var attachments = [];
  15145. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15146. for (var i = 0; i < textureCount; i++) {
  15147. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15148. var type = types[i] || defaultType;
  15149. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15150. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15151. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15152. }
  15153. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15154. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15155. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15156. }
  15157. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15158. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15159. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15160. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15161. }
  15162. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15163. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15164. textures.push(texture);
  15165. attachments.push(attachment);
  15166. gl.activeTexture(gl["TEXTURE" + i]);
  15167. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15172. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15173. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15174. if (generateMipMaps) {
  15175. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15176. }
  15177. // Unbind
  15178. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15179. texture._framebuffer = framebuffer;
  15180. texture._depthStencilBuffer = depthStencilBuffer;
  15181. texture.baseWidth = width;
  15182. texture.baseHeight = height;
  15183. texture.width = width;
  15184. texture.height = height;
  15185. texture.isReady = true;
  15186. texture.samples = 1;
  15187. texture.generateMipMaps = generateMipMaps;
  15188. texture.samplingMode = samplingMode;
  15189. texture.type = type;
  15190. texture._generateDepthBuffer = generateDepthBuffer;
  15191. texture._generateStencilBuffer = generateStencilBuffer;
  15192. texture._attachments = attachments;
  15193. this._internalTexturesCache.push(texture);
  15194. }
  15195. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15196. // Depth texture
  15197. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15198. gl.activeTexture(gl.TEXTURE0);
  15199. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15204. 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);
  15205. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15206. depthTexture._framebuffer = framebuffer;
  15207. depthTexture.baseWidth = width;
  15208. depthTexture.baseHeight = height;
  15209. depthTexture.width = width;
  15210. depthTexture.height = height;
  15211. depthTexture.isReady = true;
  15212. depthTexture.samples = 1;
  15213. depthTexture.generateMipMaps = generateMipMaps;
  15214. depthTexture.samplingMode = gl.NEAREST;
  15215. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15216. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15217. textures.push(depthTexture);
  15218. this._internalTexturesCache.push(depthTexture);
  15219. }
  15220. gl.drawBuffers(attachments);
  15221. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15222. this.bindUnboundFramebuffer(null);
  15223. this.resetTextureCache();
  15224. return textures;
  15225. };
  15226. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15227. if (samples === void 0) { samples = 1; }
  15228. var depthStencilBuffer = null;
  15229. var gl = this._gl;
  15230. // Create the depth/stencil buffer
  15231. if (generateStencilBuffer) {
  15232. depthStencilBuffer = gl.createRenderbuffer();
  15233. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15234. if (samples > 1) {
  15235. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15236. }
  15237. else {
  15238. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15239. }
  15240. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15241. }
  15242. else if (generateDepthBuffer) {
  15243. depthStencilBuffer = gl.createRenderbuffer();
  15244. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15245. if (samples > 1) {
  15246. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15247. }
  15248. else {
  15249. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15250. }
  15251. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15252. }
  15253. return depthStencilBuffer;
  15254. };
  15255. /**
  15256. * Updates the sample count of a render target texture
  15257. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15258. * @param texture defines the texture to update
  15259. * @param samples defines the sample count to set
  15260. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15261. */
  15262. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15263. if (this.webGLVersion < 2 || !texture) {
  15264. return 1;
  15265. }
  15266. if (texture.samples === samples) {
  15267. return samples;
  15268. }
  15269. var gl = this._gl;
  15270. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15271. // Dispose previous render buffers
  15272. if (texture._depthStencilBuffer) {
  15273. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15274. texture._depthStencilBuffer = null;
  15275. }
  15276. if (texture._MSAAFramebuffer) {
  15277. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15278. texture._MSAAFramebuffer = null;
  15279. }
  15280. if (texture._MSAARenderBuffer) {
  15281. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15282. texture._MSAARenderBuffer = null;
  15283. }
  15284. if (samples > 1) {
  15285. var framebuffer = gl.createFramebuffer();
  15286. if (!framebuffer) {
  15287. throw new Error("Unable to create multi sampled framebuffer");
  15288. }
  15289. texture._MSAAFramebuffer = framebuffer;
  15290. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15291. var colorRenderbuffer = gl.createRenderbuffer();
  15292. if (!colorRenderbuffer) {
  15293. throw new Error("Unable to create multi sampled framebuffer");
  15294. }
  15295. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15296. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15297. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15298. texture._MSAARenderBuffer = colorRenderbuffer;
  15299. }
  15300. else {
  15301. this.bindUnboundFramebuffer(texture._framebuffer);
  15302. }
  15303. texture.samples = samples;
  15304. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15305. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15306. this.bindUnboundFramebuffer(null);
  15307. return samples;
  15308. };
  15309. /**
  15310. * Update the sample count for a given multiple render target texture
  15311. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15312. * @param textures defines the textures to update
  15313. * @param samples defines the sample count to set
  15314. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15315. */
  15316. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15317. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15318. return 1;
  15319. }
  15320. if (textures[0].samples === samples) {
  15321. return samples;
  15322. }
  15323. var gl = this._gl;
  15324. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15325. // Dispose previous render buffers
  15326. if (textures[0]._depthStencilBuffer) {
  15327. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15328. textures[0]._depthStencilBuffer = null;
  15329. }
  15330. if (textures[0]._MSAAFramebuffer) {
  15331. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15332. textures[0]._MSAAFramebuffer = null;
  15333. }
  15334. for (var i = 0; i < textures.length; i++) {
  15335. if (textures[i]._MSAARenderBuffer) {
  15336. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15337. textures[i]._MSAARenderBuffer = null;
  15338. }
  15339. }
  15340. if (samples > 1) {
  15341. var framebuffer = gl.createFramebuffer();
  15342. if (!framebuffer) {
  15343. throw new Error("Unable to create multi sampled framebuffer");
  15344. }
  15345. this.bindUnboundFramebuffer(framebuffer);
  15346. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15347. var attachments = [];
  15348. for (var i = 0; i < textures.length; i++) {
  15349. var texture = textures[i];
  15350. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15351. var colorRenderbuffer = gl.createRenderbuffer();
  15352. if (!colorRenderbuffer) {
  15353. throw new Error("Unable to create multi sampled framebuffer");
  15354. }
  15355. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15356. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15357. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15358. texture._MSAAFramebuffer = framebuffer;
  15359. texture._MSAARenderBuffer = colorRenderbuffer;
  15360. texture.samples = samples;
  15361. texture._depthStencilBuffer = depthStencilBuffer;
  15362. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15363. attachments.push(attachment);
  15364. }
  15365. gl.drawBuffers(attachments);
  15366. }
  15367. else {
  15368. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15369. }
  15370. this.bindUnboundFramebuffer(null);
  15371. return samples;
  15372. };
  15373. /** @hidden */
  15374. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15375. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15376. };
  15377. /** @hidden */
  15378. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15379. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15380. };
  15381. /**
  15382. * Creates a new render target cube texture
  15383. * @param size defines the size of the texture
  15384. * @param options defines the options used to create the texture
  15385. * @returns a new render target cube texture stored in an InternalTexture
  15386. */
  15387. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15388. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15389. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15390. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15391. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15392. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15393. }
  15394. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15395. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15396. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15397. }
  15398. var gl = this._gl;
  15399. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15401. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15402. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15403. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15404. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15405. }
  15406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15409. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15410. for (var face = 0; face < 6; face++) {
  15411. 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);
  15412. }
  15413. // Create the framebuffer
  15414. var framebuffer = gl.createFramebuffer();
  15415. this.bindUnboundFramebuffer(framebuffer);
  15416. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15417. // MipMaps
  15418. if (fullOptions.generateMipMaps) {
  15419. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15420. }
  15421. // Unbind
  15422. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15423. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15424. this.bindUnboundFramebuffer(null);
  15425. texture._framebuffer = framebuffer;
  15426. texture.width = size;
  15427. texture.height = size;
  15428. texture.isReady = true;
  15429. texture.isCube = true;
  15430. texture.samples = 1;
  15431. texture.generateMipMaps = fullOptions.generateMipMaps;
  15432. texture.samplingMode = fullOptions.samplingMode;
  15433. texture.type = fullOptions.type;
  15434. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15435. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15436. this._internalTexturesCache.push(texture);
  15437. return texture;
  15438. };
  15439. /**
  15440. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15441. * @param rootUrl defines the url where the file to load is located
  15442. * @param scene defines the current scene
  15443. * @param scale defines scale to apply to the mip map selection
  15444. * @param offset defines offset to apply to the mip map selection
  15445. * @param onLoad defines an optional callback raised when the texture is loaded
  15446. * @param onError defines an optional callback raised if there is an issue to load the texture
  15447. * @param format defines the format of the data
  15448. * @param forcedExtension defines the extension to use to pick the right loader
  15449. * @returns the cube texture as an InternalTexture
  15450. */
  15451. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15452. var _this = this;
  15453. if (onLoad === void 0) { onLoad = null; }
  15454. if (onError === void 0) { onError = null; }
  15455. if (forcedExtension === void 0) { forcedExtension = null; }
  15456. var callback = function (loadData) {
  15457. if (!loadData) {
  15458. if (onLoad) {
  15459. onLoad(null);
  15460. }
  15461. return;
  15462. }
  15463. var texture = loadData.texture;
  15464. if (loadData.info.sphericalPolynomial) {
  15465. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15466. }
  15467. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15468. texture._lodGenerationScale = scale;
  15469. texture._lodGenerationOffset = offset;
  15470. if (_this._caps.textureLOD) {
  15471. // Do not add extra process if texture lod is supported.
  15472. if (onLoad) {
  15473. onLoad(texture);
  15474. }
  15475. return;
  15476. }
  15477. var mipSlices = 3;
  15478. var gl = _this._gl;
  15479. var width = loadData.width;
  15480. if (!width) {
  15481. return;
  15482. }
  15483. var textures = [];
  15484. for (var i = 0; i < mipSlices; i++) {
  15485. //compute LOD from even spacing in smoothness (matching shader calculation)
  15486. var smoothness = i / (mipSlices - 1);
  15487. var roughness = 1 - smoothness;
  15488. var minLODIndex = offset; // roughness = 0
  15489. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15490. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15491. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15492. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15493. glTextureFromLod.isCube = true;
  15494. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15499. if (loadData.isDDS) {
  15500. var info = loadData.info;
  15501. var data = loadData.data;
  15502. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15503. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15504. }
  15505. else {
  15506. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15507. }
  15508. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15509. // Wrap in a base texture for easy binding.
  15510. var lodTexture = new BABYLON.BaseTexture(scene);
  15511. lodTexture.isCube = true;
  15512. lodTexture._texture = glTextureFromLod;
  15513. glTextureFromLod.isReady = true;
  15514. textures.push(lodTexture);
  15515. }
  15516. texture._lodTextureHigh = textures[2];
  15517. texture._lodTextureMid = textures[1];
  15518. texture._lodTextureLow = textures[0];
  15519. if (onLoad) {
  15520. onLoad(texture);
  15521. }
  15522. };
  15523. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15524. };
  15525. /**
  15526. * Creates a cube texture
  15527. * @param rootUrl defines the url where the files to load is located
  15528. * @param scene defines the current scene
  15529. * @param files defines the list of files to load (1 per face)
  15530. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15531. * @param onLoad defines an optional callback raised when the texture is loaded
  15532. * @param onError defines an optional callback raised if there is an issue to load the texture
  15533. * @param format defines the format of the data
  15534. * @param forcedExtension defines the extension to use to pick the right loader
  15535. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15536. * @returns the cube texture as an InternalTexture
  15537. */
  15538. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15539. var _this = this;
  15540. if (onLoad === void 0) { onLoad = null; }
  15541. if (onError === void 0) { onError = null; }
  15542. if (forcedExtension === void 0) { forcedExtension = null; }
  15543. if (createPolynomials === void 0) { createPolynomials = false; }
  15544. var gl = this._gl;
  15545. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15546. texture.isCube = true;
  15547. texture.url = rootUrl;
  15548. texture.generateMipMaps = !noMipmap;
  15549. if (!this._doNotHandleContextLost) {
  15550. texture._extension = forcedExtension;
  15551. texture._files = files;
  15552. }
  15553. var isKTX = false;
  15554. var isDDS = false;
  15555. var lastDot = rootUrl.lastIndexOf('.');
  15556. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15557. if (this._textureFormatInUse) {
  15558. extension = this._textureFormatInUse;
  15559. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15560. isKTX = true;
  15561. }
  15562. else {
  15563. isDDS = (extension === ".dds");
  15564. }
  15565. var onerror = function (request, exception) {
  15566. if (onError && request) {
  15567. onError(request.status + " " + request.statusText, exception);
  15568. }
  15569. };
  15570. if (isKTX) {
  15571. this._loadFile(rootUrl, function (data) {
  15572. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15573. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15574. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15575. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15576. ktx.uploadLevels(_this._gl, !noMipmap);
  15577. _this.setCubeMapTextureParams(gl, loadMipmap);
  15578. texture.width = ktx.pixelWidth;
  15579. texture.height = ktx.pixelHeight;
  15580. texture.isReady = true;
  15581. }, undefined, undefined, true, onerror);
  15582. }
  15583. else if (isDDS) {
  15584. if (files && files.length === 6) {
  15585. this._cascadeLoadFiles(scene, function (imgs) {
  15586. var info;
  15587. var loadMipmap = false;
  15588. var width = 0;
  15589. for (var index = 0; index < imgs.length; index++) {
  15590. var data = imgs[index];
  15591. info = BABYLON.DDSTools.GetDDSInfo(data);
  15592. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15593. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15594. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15595. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15596. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15597. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15598. }
  15599. texture.width = info.width;
  15600. texture.height = info.height;
  15601. texture.type = info.textureType;
  15602. width = info.width;
  15603. }
  15604. _this.setCubeMapTextureParams(gl, loadMipmap);
  15605. texture.isReady = true;
  15606. if (onLoad) {
  15607. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15608. }
  15609. }, files, onError);
  15610. }
  15611. else {
  15612. this._loadFile(rootUrl, function (data) {
  15613. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15614. if (createPolynomials) {
  15615. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15616. }
  15617. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15618. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15619. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15620. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15621. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15622. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15623. }
  15624. _this.setCubeMapTextureParams(gl, loadMipmap);
  15625. texture.width = info.width;
  15626. texture.height = info.height;
  15627. texture.isReady = true;
  15628. texture.type = info.textureType;
  15629. if (onLoad) {
  15630. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15631. }
  15632. }, undefined, undefined, true, onerror);
  15633. }
  15634. }
  15635. else {
  15636. if (!files) {
  15637. throw new Error("Cannot load cubemap because files were not defined");
  15638. }
  15639. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15640. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15641. var height = width;
  15642. _this._prepareWorkingCanvas();
  15643. if (!_this._workingCanvas || !_this._workingContext) {
  15644. return;
  15645. }
  15646. _this._workingCanvas.width = width;
  15647. _this._workingCanvas.height = height;
  15648. var faces = [
  15649. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15650. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15651. ];
  15652. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15653. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15654. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15655. for (var index = 0; index < faces.length; index++) {
  15656. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15657. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15658. }
  15659. if (!noMipmap) {
  15660. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15661. }
  15662. _this.setCubeMapTextureParams(gl, !noMipmap);
  15663. texture.width = width;
  15664. texture.height = height;
  15665. texture.isReady = true;
  15666. if (format) {
  15667. texture.format = format;
  15668. }
  15669. texture.onLoadedObservable.notifyObservers(texture);
  15670. texture.onLoadedObservable.clear();
  15671. if (onLoad) {
  15672. onLoad();
  15673. }
  15674. }, files, onError);
  15675. }
  15676. this._internalTexturesCache.push(texture);
  15677. return texture;
  15678. };
  15679. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15684. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15685. // this.resetTextureCache();
  15686. };
  15687. /**
  15688. * Update a raw cube texture
  15689. * @param texture defines the texture to udpdate
  15690. * @param data defines the data to store
  15691. * @param format defines the data format
  15692. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15693. * @param invertY defines if data must be stored with Y axis inverted
  15694. * @param compression defines the compression used (null by default)
  15695. * @param level defines which level of the texture to update
  15696. */
  15697. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15698. if (compression === void 0) { compression = null; }
  15699. if (level === void 0) { level = 0; }
  15700. texture._bufferViewArray = data;
  15701. texture.format = format;
  15702. texture.type = type;
  15703. texture.invertY = invertY;
  15704. texture._compression = compression;
  15705. var gl = this._gl;
  15706. var textureType = this._getWebGLTextureType(type);
  15707. var internalFormat = this._getInternalFormat(format);
  15708. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15709. var needConversion = false;
  15710. if (internalFormat === gl.RGB) {
  15711. internalFormat = gl.RGBA;
  15712. needConversion = true;
  15713. }
  15714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15715. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15716. if (texture.width % 4 !== 0) {
  15717. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15718. }
  15719. // Data are known to be in +X +Y +Z -X -Y -Z
  15720. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15721. var faceData = data[faceIndex];
  15722. if (compression) {
  15723. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15724. }
  15725. else {
  15726. if (needConversion) {
  15727. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15728. }
  15729. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15730. }
  15731. }
  15732. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15733. if (isPot && texture.generateMipMaps && level === 0) {
  15734. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15735. }
  15736. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15737. // this.resetTextureCache();
  15738. texture.isReady = true;
  15739. };
  15740. /**
  15741. * Creates a new raw cube texture
  15742. * @param data defines the array of data to use to create each face
  15743. * @param size defines the size of the textures
  15744. * @param format defines the format of the data
  15745. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15746. * @param generateMipMaps defines if the engine should generate the mip levels
  15747. * @param invertY defines if data must be stored with Y axis inverted
  15748. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15749. * @param compression defines the compression used (null by default)
  15750. * @returns the cube texture as an InternalTexture
  15751. */
  15752. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15753. if (compression === void 0) { compression = null; }
  15754. var gl = this._gl;
  15755. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15756. texture.isCube = true;
  15757. texture.generateMipMaps = generateMipMaps;
  15758. texture.format = format;
  15759. texture.type = type;
  15760. if (!this._doNotHandleContextLost) {
  15761. texture._bufferViewArray = data;
  15762. }
  15763. var textureType = this._getWebGLTextureType(type);
  15764. var internalFormat = this._getInternalFormat(format);
  15765. if (internalFormat === gl.RGB) {
  15766. internalFormat = gl.RGBA;
  15767. }
  15768. var width = size;
  15769. var height = width;
  15770. texture.width = width;
  15771. texture.height = height;
  15772. // Double check on POT to generate Mips.
  15773. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15774. if (!isPot) {
  15775. generateMipMaps = false;
  15776. }
  15777. // Upload data if needed. The texture won't be ready until then.
  15778. if (data) {
  15779. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15780. }
  15781. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15782. // Filters
  15783. if (data && generateMipMaps) {
  15784. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15785. }
  15786. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15789. }
  15790. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15793. }
  15794. else {
  15795. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15798. }
  15799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15801. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15802. return texture;
  15803. };
  15804. /**
  15805. * Creates a new raw cube texture from a specified url
  15806. * @param url defines the url where the data is located
  15807. * @param scene defines the current scene
  15808. * @param size defines the size of the textures
  15809. * @param format defines the format of the data
  15810. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15811. * @param noMipmap defines if the engine should avoid generating the mip levels
  15812. * @param callback defines a callback used to extract texture data from loaded data
  15813. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15814. * @param onLoad defines a callback called when texture is loaded
  15815. * @param onError defines a callback called if there is an error
  15816. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15817. * @param invertY defines if data must be stored with Y axis inverted
  15818. * @returns the cube texture as an InternalTexture
  15819. */
  15820. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15821. var _this = this;
  15822. if (onLoad === void 0) { onLoad = null; }
  15823. if (onError === void 0) { onError = null; }
  15824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15825. if (invertY === void 0) { invertY = false; }
  15826. var gl = this._gl;
  15827. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15828. scene._addPendingData(texture);
  15829. texture.url = url;
  15830. this._internalTexturesCache.push(texture);
  15831. var onerror = function (request, exception) {
  15832. scene._removePendingData(texture);
  15833. if (onError && request) {
  15834. onError(request.status + " " + request.statusText, exception);
  15835. }
  15836. };
  15837. var internalCallback = function (data) {
  15838. var width = texture.width;
  15839. var faceDataArrays = callback(data);
  15840. if (!faceDataArrays) {
  15841. return;
  15842. }
  15843. if (mipmapGenerator) {
  15844. var textureType = _this._getWebGLTextureType(type);
  15845. var internalFormat = _this._getInternalFormat(format);
  15846. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15847. var needConversion = false;
  15848. if (internalFormat === gl.RGB) {
  15849. internalFormat = gl.RGBA;
  15850. needConversion = true;
  15851. }
  15852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15853. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15854. var mipData = mipmapGenerator(faceDataArrays);
  15855. for (var level = 0; level < mipData.length; level++) {
  15856. var mipSize = width >> level;
  15857. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15858. var mipFaceData = mipData[level][faceIndex];
  15859. if (needConversion) {
  15860. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15861. }
  15862. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15863. }
  15864. }
  15865. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15866. }
  15867. else {
  15868. texture.generateMipMaps = !noMipmap;
  15869. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15870. }
  15871. texture.isReady = true;
  15872. // this.resetTextureCache();
  15873. scene._removePendingData(texture);
  15874. if (onLoad) {
  15875. onLoad();
  15876. }
  15877. };
  15878. this._loadFile(url, function (data) {
  15879. internalCallback(data);
  15880. }, undefined, scene.database, true, onerror);
  15881. return texture;
  15882. };
  15883. ;
  15884. /**
  15885. * Update a raw 3D texture
  15886. * @param texture defines the texture to update
  15887. * @param data defines the data to store
  15888. * @param format defines the data format
  15889. * @param invertY defines if data must be stored with Y axis inverted
  15890. * @param compression defines the used compression (can be null)
  15891. */
  15892. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15893. if (compression === void 0) { compression = null; }
  15894. var internalFormat = this._getInternalFormat(format);
  15895. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15896. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15897. if (!this._doNotHandleContextLost) {
  15898. texture._bufferView = data;
  15899. texture.format = format;
  15900. texture.invertY = invertY;
  15901. texture._compression = compression;
  15902. }
  15903. if (texture.width % 4 !== 0) {
  15904. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15905. }
  15906. if (compression && data) {
  15907. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15908. }
  15909. else {
  15910. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15911. }
  15912. if (texture.generateMipMaps) {
  15913. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15914. }
  15915. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15916. // this.resetTextureCache();
  15917. texture.isReady = true;
  15918. };
  15919. /**
  15920. * Creates a new raw 3D texture
  15921. * @param data defines the data used to create the texture
  15922. * @param width defines the width of the texture
  15923. * @param height defines the height of the texture
  15924. * @param depth defines the depth of the texture
  15925. * @param format defines the format of the texture
  15926. * @param generateMipMaps defines if the engine must generate mip levels
  15927. * @param invertY defines if data must be stored with Y axis inverted
  15928. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15929. * @param compression defines the compressed used (can be null)
  15930. * @returns a new raw 3D texture (stored in an InternalTexture)
  15931. */
  15932. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15933. if (compression === void 0) { compression = null; }
  15934. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15935. texture.baseWidth = width;
  15936. texture.baseHeight = height;
  15937. texture.baseDepth = depth;
  15938. texture.width = width;
  15939. texture.height = height;
  15940. texture.depth = depth;
  15941. texture.format = format;
  15942. texture.generateMipMaps = generateMipMaps;
  15943. texture.samplingMode = samplingMode;
  15944. texture.is3D = true;
  15945. if (!this._doNotHandleContextLost) {
  15946. texture._bufferView = data;
  15947. }
  15948. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15949. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15950. // Filters
  15951. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15952. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15953. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15954. if (generateMipMaps) {
  15955. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15956. }
  15957. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15958. this._internalTexturesCache.push(texture);
  15959. return texture;
  15960. };
  15961. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15962. var gl = this._gl;
  15963. if (!gl) {
  15964. return;
  15965. }
  15966. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15969. if (!noMipmap && !isCompressed) {
  15970. gl.generateMipmap(gl.TEXTURE_2D);
  15971. }
  15972. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15973. // this.resetTextureCache();
  15974. if (scene) {
  15975. scene._removePendingData(texture);
  15976. }
  15977. texture.onLoadedObservable.notifyObservers(texture);
  15978. texture.onLoadedObservable.clear();
  15979. };
  15980. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15981. var _this = this;
  15982. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15983. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15984. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15985. var gl = this._gl;
  15986. if (!gl) {
  15987. return;
  15988. }
  15989. if (!texture._webGLTexture) {
  15990. // this.resetTextureCache();
  15991. if (scene) {
  15992. scene._removePendingData(texture);
  15993. }
  15994. return;
  15995. }
  15996. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15997. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15998. texture.baseWidth = width;
  15999. texture.baseHeight = height;
  16000. texture.width = potWidth;
  16001. texture.height = potHeight;
  16002. texture.isReady = true;
  16003. if (processFunction(potWidth, potHeight, function () {
  16004. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16005. })) {
  16006. // Returning as texture needs extra async steps
  16007. return;
  16008. }
  16009. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16010. };
  16011. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16012. // Create new RGBA data container.
  16013. var rgbaData;
  16014. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16015. rgbaData = new Float32Array(width * height * 4);
  16016. }
  16017. else {
  16018. rgbaData = new Uint32Array(width * height * 4);
  16019. }
  16020. // Convert each pixel.
  16021. for (var x = 0; x < width; x++) {
  16022. for (var y = 0; y < height; y++) {
  16023. var index = (y * width + x) * 3;
  16024. var newIndex = (y * width + x) * 4;
  16025. // Map Old Value to new value.
  16026. rgbaData[newIndex + 0] = rgbData[index + 0];
  16027. rgbaData[newIndex + 1] = rgbData[index + 1];
  16028. rgbaData[newIndex + 2] = rgbData[index + 2];
  16029. // Add fully opaque alpha channel.
  16030. rgbaData[newIndex + 3] = 1;
  16031. }
  16032. }
  16033. return rgbaData;
  16034. };
  16035. /** @hidden */
  16036. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16037. var gl = this._gl;
  16038. if (texture._framebuffer) {
  16039. gl.deleteFramebuffer(texture._framebuffer);
  16040. texture._framebuffer = null;
  16041. }
  16042. if (texture._depthStencilBuffer) {
  16043. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16044. texture._depthStencilBuffer = null;
  16045. }
  16046. if (texture._MSAAFramebuffer) {
  16047. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16048. texture._MSAAFramebuffer = null;
  16049. }
  16050. if (texture._MSAARenderBuffer) {
  16051. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16052. texture._MSAARenderBuffer = null;
  16053. }
  16054. };
  16055. /** @hidden */
  16056. Engine.prototype._releaseTexture = function (texture) {
  16057. var gl = this._gl;
  16058. this._releaseFramebufferObjects(texture);
  16059. gl.deleteTexture(texture._webGLTexture);
  16060. // Unbind channels
  16061. this.unbindAllTextures();
  16062. var index = this._internalTexturesCache.indexOf(texture);
  16063. if (index !== -1) {
  16064. this._internalTexturesCache.splice(index, 1);
  16065. }
  16066. // Integrated fixed lod samplers.
  16067. if (texture._lodTextureHigh) {
  16068. texture._lodTextureHigh.dispose();
  16069. }
  16070. if (texture._lodTextureMid) {
  16071. texture._lodTextureMid.dispose();
  16072. }
  16073. if (texture._lodTextureLow) {
  16074. texture._lodTextureLow.dispose();
  16075. }
  16076. // Set output texture of post process to null if the texture has been released/disposed
  16077. this.scenes.forEach(function (scene) {
  16078. scene.postProcesses.forEach(function (postProcess) {
  16079. if (postProcess._outputTexture == texture) {
  16080. postProcess._outputTexture = null;
  16081. }
  16082. });
  16083. scene.cameras.forEach(function (camera) {
  16084. camera._postProcesses.forEach(function (postProcess) {
  16085. if (postProcess) {
  16086. if (postProcess._outputTexture == texture) {
  16087. postProcess._outputTexture = null;
  16088. }
  16089. }
  16090. });
  16091. });
  16092. });
  16093. };
  16094. Engine.prototype.setProgram = function (program) {
  16095. if (this._currentProgram !== program) {
  16096. this._gl.useProgram(program);
  16097. this._currentProgram = program;
  16098. }
  16099. };
  16100. /**
  16101. * Binds an effect to the webGL context
  16102. * @param effect defines the effect to bind
  16103. */
  16104. Engine.prototype.bindSamplers = function (effect) {
  16105. this.setProgram(effect.getProgram());
  16106. var samplers = effect.getSamplers();
  16107. for (var index = 0; index < samplers.length; index++) {
  16108. var uniform = effect.getUniform(samplers[index]);
  16109. if (uniform) {
  16110. this._boundUniforms[index] = uniform;
  16111. }
  16112. }
  16113. this._currentEffect = null;
  16114. };
  16115. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16116. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16117. return;
  16118. }
  16119. // Remove
  16120. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16121. // Bind last to it
  16122. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16123. // Bind to dummy
  16124. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16125. };
  16126. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16127. if (!internalTexture) {
  16128. return -1;
  16129. }
  16130. internalTexture._initialSlot = channel;
  16131. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16132. if (channel !== internalTexture._designatedSlot) {
  16133. this._textureCollisions.addCount(1, false);
  16134. }
  16135. }
  16136. else {
  16137. if (channel !== internalTexture._designatedSlot) {
  16138. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16139. return internalTexture._designatedSlot;
  16140. }
  16141. else {
  16142. // No slot for this texture, let's pick a new one (if we find a free slot)
  16143. if (this._nextFreeTextureSlots.length) {
  16144. return this._nextFreeTextureSlots[0];
  16145. }
  16146. // We need to recycle the oldest bound texture, sorry.
  16147. this._textureCollisions.addCount(1, false);
  16148. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16149. }
  16150. }
  16151. }
  16152. return channel;
  16153. };
  16154. Engine.prototype._linkTrackers = function (previous, next) {
  16155. previous.next = next;
  16156. next.previous = previous;
  16157. };
  16158. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16159. var currentSlot = internalTexture._designatedSlot;
  16160. if (currentSlot === -1) {
  16161. return -1;
  16162. }
  16163. internalTexture._designatedSlot = -1;
  16164. if (this.disableTextureBindingOptimization) {
  16165. return -1;
  16166. }
  16167. // Remove from bound list
  16168. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16169. // Free the slot
  16170. this._boundTexturesCache[currentSlot] = null;
  16171. this._nextFreeTextureSlots.push(currentSlot);
  16172. return currentSlot;
  16173. };
  16174. Engine.prototype._activateCurrentTexture = function () {
  16175. if (this._currentTextureChannel !== this._activeChannel) {
  16176. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16177. this._currentTextureChannel = this._activeChannel;
  16178. }
  16179. };
  16180. /** @hidden */
  16181. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16182. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16183. if (force === void 0) { force = false; }
  16184. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16185. this._activeChannel = texture._designatedSlot;
  16186. }
  16187. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16188. var isTextureForRendering = texture && texture._initialSlot > -1;
  16189. if (currentTextureBound !== texture || force) {
  16190. if (currentTextureBound) {
  16191. this._removeDesignatedSlot(currentTextureBound);
  16192. }
  16193. this._activateCurrentTexture();
  16194. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16195. this._boundTexturesCache[this._activeChannel] = texture;
  16196. if (texture) {
  16197. if (!this.disableTextureBindingOptimization) {
  16198. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16199. if (slotIndex > -1) {
  16200. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16201. }
  16202. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16203. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16204. }
  16205. texture._designatedSlot = this._activeChannel;
  16206. }
  16207. }
  16208. else if (forTextureDataUpdate) {
  16209. this._activateCurrentTexture();
  16210. }
  16211. if (isTextureForRendering && !forTextureDataUpdate) {
  16212. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16213. }
  16214. };
  16215. /** @hidden */
  16216. Engine.prototype._bindTexture = function (channel, texture) {
  16217. if (channel < 0) {
  16218. return;
  16219. }
  16220. if (texture) {
  16221. channel = this._getCorrectTextureChannel(channel, texture);
  16222. }
  16223. this._activeChannel = channel;
  16224. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16225. };
  16226. /**
  16227. * Sets a texture to the webGL context from a postprocess
  16228. * @param channel defines the channel to use
  16229. * @param postProcess defines the source postprocess
  16230. */
  16231. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16232. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16233. };
  16234. /**
  16235. * Binds the output of the passed in post process to the texture channel specified
  16236. * @param channel The channel the texture should be bound to
  16237. * @param postProcess The post process which's output should be bound
  16238. */
  16239. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16240. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16241. };
  16242. /**
  16243. * Unbind all textures from the webGL context
  16244. */
  16245. Engine.prototype.unbindAllTextures = function () {
  16246. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16247. this._activeChannel = channel;
  16248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16249. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16250. if (this.webGLVersion > 1) {
  16251. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16252. }
  16253. }
  16254. };
  16255. /**
  16256. * Sets a texture to the according uniform.
  16257. * @param channel The texture channel
  16258. * @param uniform The uniform to set
  16259. * @param texture The texture to apply
  16260. */
  16261. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16262. if (channel < 0) {
  16263. return;
  16264. }
  16265. if (uniform) {
  16266. this._boundUniforms[channel] = uniform;
  16267. }
  16268. this._setTexture(channel, texture);
  16269. };
  16270. /**
  16271. * Sets a depth stencil texture from a render target to the according uniform.
  16272. * @param channel The texture channel
  16273. * @param uniform The uniform to set
  16274. * @param texture The render target texture containing the depth stencil texture to apply
  16275. */
  16276. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16277. if (channel < 0) {
  16278. return;
  16279. }
  16280. if (uniform) {
  16281. this._boundUniforms[channel] = uniform;
  16282. }
  16283. if (!texture || !texture.depthStencilTexture) {
  16284. this._setTexture(channel, null);
  16285. }
  16286. else {
  16287. this._setTexture(channel, texture, false, true);
  16288. }
  16289. };
  16290. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16291. var uniform = this._boundUniforms[sourceSlot];
  16292. if (uniform._currentState === destination) {
  16293. return;
  16294. }
  16295. this._gl.uniform1i(uniform, destination);
  16296. uniform._currentState = destination;
  16297. };
  16298. Engine.prototype._getTextureWrapMode = function (mode) {
  16299. switch (mode) {
  16300. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16301. return this._gl.REPEAT;
  16302. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16303. return this._gl.CLAMP_TO_EDGE;
  16304. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16305. return this._gl.MIRRORED_REPEAT;
  16306. }
  16307. return this._gl.REPEAT;
  16308. };
  16309. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16310. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16311. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16312. // Not ready?
  16313. if (!texture) {
  16314. if (this._boundTexturesCache[channel] != null) {
  16315. this._activeChannel = channel;
  16316. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16318. if (this.webGLVersion > 1) {
  16319. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16320. }
  16321. }
  16322. return false;
  16323. }
  16324. // Video
  16325. if (texture.video) {
  16326. this._activeChannel = channel;
  16327. texture.update();
  16328. }
  16329. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16330. texture.delayLoad();
  16331. return false;
  16332. }
  16333. var internalTexture;
  16334. if (depthStencilTexture) {
  16335. internalTexture = texture.depthStencilTexture;
  16336. }
  16337. else if (texture.isReady()) {
  16338. internalTexture = texture.getInternalTexture();
  16339. }
  16340. else if (texture.isCube) {
  16341. internalTexture = this.emptyCubeTexture;
  16342. }
  16343. else if (texture.is3D) {
  16344. internalTexture = this.emptyTexture3D;
  16345. }
  16346. else {
  16347. internalTexture = this.emptyTexture;
  16348. }
  16349. if (!isPartOfTextureArray) {
  16350. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16351. }
  16352. var needToBind = true;
  16353. if (this._boundTexturesCache[channel] === internalTexture) {
  16354. this._moveBoundTextureOnTop(internalTexture);
  16355. if (!isPartOfTextureArray) {
  16356. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16357. }
  16358. needToBind = false;
  16359. }
  16360. this._activeChannel = channel;
  16361. if (internalTexture && internalTexture.is3D) {
  16362. if (needToBind) {
  16363. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16364. }
  16365. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16366. internalTexture._cachedWrapU = texture.wrapU;
  16367. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16368. }
  16369. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16370. internalTexture._cachedWrapV = texture.wrapV;
  16371. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16372. }
  16373. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16374. internalTexture._cachedWrapR = texture.wrapR;
  16375. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16376. }
  16377. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16378. }
  16379. else if (internalTexture && internalTexture.isCube) {
  16380. if (needToBind) {
  16381. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16382. }
  16383. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16384. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16385. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16386. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16387. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16388. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16389. }
  16390. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16391. }
  16392. else {
  16393. if (needToBind) {
  16394. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16395. }
  16396. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16397. internalTexture._cachedWrapU = texture.wrapU;
  16398. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16399. }
  16400. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16401. internalTexture._cachedWrapV = texture.wrapV;
  16402. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16403. }
  16404. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16405. }
  16406. return true;
  16407. };
  16408. /**
  16409. * Sets an array of texture to the webGL context
  16410. * @param channel defines the channel where the texture array must be set
  16411. * @param uniform defines the associated uniform location
  16412. * @param textures defines the array of textures to bind
  16413. */
  16414. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16415. if (channel < 0 || !uniform) {
  16416. return;
  16417. }
  16418. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16419. this._textureUnits = new Int32Array(textures.length);
  16420. }
  16421. for (var i = 0; i < textures.length; i++) {
  16422. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16423. }
  16424. this._gl.uniform1iv(uniform, this._textureUnits);
  16425. for (var index = 0; index < textures.length; index++) {
  16426. this._setTexture(this._textureUnits[index], textures[index], true);
  16427. }
  16428. };
  16429. /** @hidden */
  16430. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16431. var internalTexture = texture.getInternalTexture();
  16432. if (!internalTexture) {
  16433. return;
  16434. }
  16435. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16436. var value = texture.anisotropicFilteringLevel;
  16437. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16438. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16439. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16440. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16441. }
  16442. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16443. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16444. internalTexture._cachedAnisotropicFilteringLevel = value;
  16445. }
  16446. };
  16447. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16448. this._bindTextureDirectly(target, texture, true, true);
  16449. this._gl.texParameterf(target, parameter, value);
  16450. };
  16451. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16452. if (texture) {
  16453. this._bindTextureDirectly(target, texture, true, true);
  16454. }
  16455. this._gl.texParameteri(target, parameter, value);
  16456. };
  16457. /**
  16458. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16459. * @param x defines the x coordinate of the rectangle where pixels must be read
  16460. * @param y defines the y coordinate of the rectangle where pixels must be read
  16461. * @param width defines the width of the rectangle where pixels must be read
  16462. * @param height defines the height of the rectangle where pixels must be read
  16463. * @returns a Uint8Array containing RGBA colors
  16464. */
  16465. Engine.prototype.readPixels = function (x, y, width, height) {
  16466. var data = new Uint8Array(height * width * 4);
  16467. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16468. return data;
  16469. };
  16470. /**
  16471. * Add an externaly attached data from its key.
  16472. * This method call will fail and return false, if such key already exists.
  16473. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16474. * @param key the unique key that identifies the data
  16475. * @param data the data object to associate to the key for this Engine instance
  16476. * @return true if no such key were already present and the data was added successfully, false otherwise
  16477. */
  16478. Engine.prototype.addExternalData = function (key, data) {
  16479. if (!this._externalData) {
  16480. this._externalData = new BABYLON.StringDictionary();
  16481. }
  16482. return this._externalData.add(key, data);
  16483. };
  16484. /**
  16485. * Get an externaly attached data from its key
  16486. * @param key the unique key that identifies the data
  16487. * @return the associated data, if present (can be null), or undefined if not present
  16488. */
  16489. Engine.prototype.getExternalData = function (key) {
  16490. if (!this._externalData) {
  16491. this._externalData = new BABYLON.StringDictionary();
  16492. }
  16493. return this._externalData.get(key);
  16494. };
  16495. /**
  16496. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16497. * @param key the unique key that identifies the data
  16498. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16499. * @return the associated data, can be null if the factory returned null.
  16500. */
  16501. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16502. if (!this._externalData) {
  16503. this._externalData = new BABYLON.StringDictionary();
  16504. }
  16505. return this._externalData.getOrAddWithFactory(key, factory);
  16506. };
  16507. /**
  16508. * Remove an externaly attached data from the Engine instance
  16509. * @param key the unique key that identifies the data
  16510. * @return true if the data was successfully removed, false if it doesn't exist
  16511. */
  16512. Engine.prototype.removeExternalData = function (key) {
  16513. if (!this._externalData) {
  16514. this._externalData = new BABYLON.StringDictionary();
  16515. }
  16516. return this._externalData.remove(key);
  16517. };
  16518. /**
  16519. * Unbind all vertex attributes from the webGL context
  16520. */
  16521. Engine.prototype.unbindAllAttributes = function () {
  16522. if (this._mustWipeVertexAttributes) {
  16523. this._mustWipeVertexAttributes = false;
  16524. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16525. this._gl.disableVertexAttribArray(i);
  16526. this._vertexAttribArraysEnabled[i] = false;
  16527. this._currentBufferPointers[i].active = false;
  16528. }
  16529. return;
  16530. }
  16531. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16532. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16533. continue;
  16534. }
  16535. this._gl.disableVertexAttribArray(i);
  16536. this._vertexAttribArraysEnabled[i] = false;
  16537. this._currentBufferPointers[i].active = false;
  16538. }
  16539. };
  16540. /**
  16541. * 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
  16542. */
  16543. Engine.prototype.releaseEffects = function () {
  16544. for (var name in this._compiledEffects) {
  16545. this._deleteProgram(this._compiledEffects[name]._program);
  16546. }
  16547. this._compiledEffects = {};
  16548. };
  16549. /**
  16550. * Dispose and release all associated resources
  16551. */
  16552. Engine.prototype.dispose = function () {
  16553. this.hideLoadingUI();
  16554. this.stopRenderLoop();
  16555. // Release postProcesses
  16556. while (this.postProcesses.length) {
  16557. this.postProcesses[0].dispose();
  16558. }
  16559. // Empty texture
  16560. if (this._emptyTexture) {
  16561. this._releaseTexture(this._emptyTexture);
  16562. this._emptyTexture = null;
  16563. }
  16564. if (this._emptyCubeTexture) {
  16565. this._releaseTexture(this._emptyCubeTexture);
  16566. this._emptyCubeTexture = null;
  16567. }
  16568. // Rescale PP
  16569. if (this._rescalePostProcess) {
  16570. this._rescalePostProcess.dispose();
  16571. }
  16572. // Release scenes
  16573. while (this.scenes.length) {
  16574. this.scenes[0].dispose();
  16575. }
  16576. // Release audio engine
  16577. if (Engine.audioEngine) {
  16578. Engine.audioEngine.dispose();
  16579. }
  16580. // Release effects
  16581. this.releaseEffects();
  16582. // Unbind
  16583. this.unbindAllAttributes();
  16584. this._boundUniforms = [];
  16585. if (this._dummyFramebuffer) {
  16586. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16587. }
  16588. //WebVR
  16589. this.disableVR();
  16590. // Events
  16591. if (BABYLON.Tools.IsWindowObjectExist()) {
  16592. window.removeEventListener("blur", this._onBlur);
  16593. window.removeEventListener("focus", this._onFocus);
  16594. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16595. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16596. if (this._renderingCanvas) {
  16597. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16598. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16599. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16600. if (!this._doNotHandleContextLost) {
  16601. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16602. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16603. }
  16604. }
  16605. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16606. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16607. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16608. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16609. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16610. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16611. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16612. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16613. if (this._onVrDisplayConnect) {
  16614. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16615. if (this._onVrDisplayDisconnect) {
  16616. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16617. }
  16618. if (this._onVrDisplayPresentChange) {
  16619. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16620. }
  16621. this._onVrDisplayConnect = null;
  16622. this._onVrDisplayDisconnect = null;
  16623. }
  16624. }
  16625. // Remove from Instances
  16626. var index = Engine.Instances.indexOf(this);
  16627. if (index >= 0) {
  16628. Engine.Instances.splice(index, 1);
  16629. }
  16630. this._workingCanvas = null;
  16631. this._workingContext = null;
  16632. this._currentBufferPointers = [];
  16633. this._renderingCanvas = null;
  16634. this._currentProgram = null;
  16635. this._bindedRenderFunction = null;
  16636. this.onResizeObservable.clear();
  16637. this.onCanvasBlurObservable.clear();
  16638. this.onCanvasFocusObservable.clear();
  16639. this.onCanvasPointerOutObservable.clear();
  16640. this.onBeginFrameObservable.clear();
  16641. this.onEndFrameObservable.clear();
  16642. BABYLON.Effect.ResetCache();
  16643. // Abort active requests
  16644. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16645. var request = _a[_i];
  16646. request.abort();
  16647. }
  16648. };
  16649. // Loading screen
  16650. /**
  16651. * Display the loading screen
  16652. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16653. */
  16654. Engine.prototype.displayLoadingUI = function () {
  16655. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16656. return;
  16657. }
  16658. var loadingScreen = this.loadingScreen;
  16659. if (loadingScreen) {
  16660. loadingScreen.displayLoadingUI();
  16661. }
  16662. };
  16663. /**
  16664. * Hide the loading screen
  16665. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16666. */
  16667. Engine.prototype.hideLoadingUI = function () {
  16668. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16669. return;
  16670. }
  16671. var loadingScreen = this.loadingScreen;
  16672. if (loadingScreen) {
  16673. loadingScreen.hideLoadingUI();
  16674. }
  16675. };
  16676. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16677. /**
  16678. * Gets the current loading screen object
  16679. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16680. */
  16681. get: function () {
  16682. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16683. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16684. return this._loadingScreen;
  16685. },
  16686. /**
  16687. * Sets the current loading screen object
  16688. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16689. */
  16690. set: function (loadingScreen) {
  16691. this._loadingScreen = loadingScreen;
  16692. },
  16693. enumerable: true,
  16694. configurable: true
  16695. });
  16696. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16697. /**
  16698. * Sets the current loading screen text
  16699. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16700. */
  16701. set: function (text) {
  16702. this.loadingScreen.loadingUIText = text;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16708. /**
  16709. * Sets the current loading screen background color
  16710. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16711. */
  16712. set: function (color) {
  16713. this.loadingScreen.loadingUIBackgroundColor = color;
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. /**
  16719. * Attach a new callback raised when context lost event is fired
  16720. * @param callback defines the callback to call
  16721. */
  16722. Engine.prototype.attachContextLostEvent = function (callback) {
  16723. if (this._renderingCanvas) {
  16724. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16725. }
  16726. };
  16727. /**
  16728. * Attach a new callback raised when context restored event is fired
  16729. * @param callback defines the callback to call
  16730. */
  16731. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16732. if (this._renderingCanvas) {
  16733. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16734. }
  16735. };
  16736. /**
  16737. * Gets the source code of the vertex shader associated with a specific webGL program
  16738. * @param program defines the program to use
  16739. * @returns a string containing the source code of the vertex shader associated with the program
  16740. */
  16741. Engine.prototype.getVertexShaderSource = function (program) {
  16742. var shaders = this._gl.getAttachedShaders(program);
  16743. if (!shaders) {
  16744. return null;
  16745. }
  16746. return this._gl.getShaderSource(shaders[0]);
  16747. };
  16748. /**
  16749. * Gets the source code of the fragment shader associated with a specific webGL program
  16750. * @param program defines the program to use
  16751. * @returns a string containing the source code of the fragment shader associated with the program
  16752. */
  16753. Engine.prototype.getFragmentShaderSource = function (program) {
  16754. var shaders = this._gl.getAttachedShaders(program);
  16755. if (!shaders) {
  16756. return null;
  16757. }
  16758. return this._gl.getShaderSource(shaders[1]);
  16759. };
  16760. /**
  16761. * Get the current error code of the webGL context
  16762. * @returns the error code
  16763. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16764. */
  16765. Engine.prototype.getError = function () {
  16766. return this._gl.getError();
  16767. };
  16768. // FPS
  16769. /**
  16770. * Gets the current framerate
  16771. * @returns a number representing the framerate
  16772. */
  16773. Engine.prototype.getFps = function () {
  16774. return this._fps;
  16775. };
  16776. /**
  16777. * Gets the time spent between current and previous frame
  16778. * @returns a number representing the delta time in ms
  16779. */
  16780. Engine.prototype.getDeltaTime = function () {
  16781. return this._deltaTime;
  16782. };
  16783. Engine.prototype._measureFps = function () {
  16784. this._performanceMonitor.sampleFrame();
  16785. this._fps = this._performanceMonitor.averageFPS;
  16786. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16787. };
  16788. /** @hidden */
  16789. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16790. if (faceIndex === void 0) { faceIndex = -1; }
  16791. var gl = this._gl;
  16792. if (!this._dummyFramebuffer) {
  16793. var dummy = gl.createFramebuffer();
  16794. if (!dummy) {
  16795. throw new Error("Unable to create dummy framebuffer");
  16796. }
  16797. this._dummyFramebuffer = dummy;
  16798. }
  16799. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16800. if (faceIndex > -1) {
  16801. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16802. }
  16803. else {
  16804. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16805. }
  16806. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16807. var buffer;
  16808. switch (readType) {
  16809. case gl.UNSIGNED_BYTE:
  16810. buffer = new Uint8Array(4 * width * height);
  16811. readType = gl.UNSIGNED_BYTE;
  16812. break;
  16813. default:
  16814. buffer = new Float32Array(4 * width * height);
  16815. readType = gl.FLOAT;
  16816. break;
  16817. }
  16818. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16819. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16820. return buffer;
  16821. };
  16822. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16823. if (this._webGLVersion > 1) {
  16824. return this._caps.colorBufferFloat;
  16825. }
  16826. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16827. };
  16828. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16829. if (this._webGLVersion > 1) {
  16830. return this._caps.colorBufferFloat;
  16831. }
  16832. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16833. };
  16834. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16835. Engine.prototype._canRenderToFramebuffer = function (type) {
  16836. var gl = this._gl;
  16837. //clear existing errors
  16838. while (gl.getError() !== gl.NO_ERROR) { }
  16839. var successful = true;
  16840. var texture = gl.createTexture();
  16841. gl.bindTexture(gl.TEXTURE_2D, texture);
  16842. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16843. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16845. var fb = gl.createFramebuffer();
  16846. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16847. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16848. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16849. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16850. successful = successful && (gl.getError() === gl.NO_ERROR);
  16851. //try render by clearing frame buffer's color buffer
  16852. if (successful) {
  16853. gl.clear(gl.COLOR_BUFFER_BIT);
  16854. successful = successful && (gl.getError() === gl.NO_ERROR);
  16855. }
  16856. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16857. if (successful) {
  16858. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16859. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16860. var readFormat = gl.RGBA;
  16861. var readType = gl.UNSIGNED_BYTE;
  16862. var buffer = new Uint8Array(4);
  16863. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16864. successful = successful && (gl.getError() === gl.NO_ERROR);
  16865. }
  16866. //clean up
  16867. gl.deleteTexture(texture);
  16868. gl.deleteFramebuffer(fb);
  16869. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16870. //clear accumulated errors
  16871. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16872. return successful;
  16873. };
  16874. /** @hidden */
  16875. Engine.prototype._getWebGLTextureType = function (type) {
  16876. if (type === Engine.TEXTURETYPE_FLOAT) {
  16877. return this._gl.FLOAT;
  16878. }
  16879. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16880. // Add Half Float Constant.
  16881. return this._gl.HALF_FLOAT_OES;
  16882. }
  16883. return this._gl.UNSIGNED_BYTE;
  16884. };
  16885. ;
  16886. Engine.prototype._getInternalFormat = function (format) {
  16887. var internalFormat = this._gl.RGBA;
  16888. switch (format) {
  16889. case Engine.TEXTUREFORMAT_ALPHA:
  16890. internalFormat = this._gl.ALPHA;
  16891. break;
  16892. case Engine.TEXTUREFORMAT_LUMINANCE:
  16893. internalFormat = this._gl.LUMINANCE;
  16894. break;
  16895. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16896. internalFormat = this._gl.LUMINANCE_ALPHA;
  16897. break;
  16898. case Engine.TEXTUREFORMAT_RGB:
  16899. case Engine.TEXTUREFORMAT_RGB32F:
  16900. internalFormat = this._gl.RGB;
  16901. break;
  16902. case Engine.TEXTUREFORMAT_RGBA:
  16903. case Engine.TEXTUREFORMAT_RGBA32F:
  16904. internalFormat = this._gl.RGBA;
  16905. break;
  16906. case Engine.TEXTUREFORMAT_R32F:
  16907. internalFormat = this._gl.RED;
  16908. break;
  16909. case Engine.TEXTUREFORMAT_RG32F:
  16910. internalFormat = this._gl.RG;
  16911. break;
  16912. }
  16913. return internalFormat;
  16914. };
  16915. /** @hidden */
  16916. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16917. if (this._webGLVersion === 1) {
  16918. if (format) {
  16919. switch (format) {
  16920. case Engine.TEXTUREFORMAT_LUMINANCE:
  16921. return this._gl.LUMINANCE;
  16922. }
  16923. }
  16924. return this._gl.RGBA;
  16925. }
  16926. if (type === Engine.TEXTURETYPE_FLOAT) {
  16927. if (format) {
  16928. switch (format) {
  16929. case Engine.TEXTUREFORMAT_R32F:
  16930. return this._gl.R32F;
  16931. case Engine.TEXTUREFORMAT_RG32F:
  16932. return this._gl.RG32F;
  16933. case Engine.TEXTUREFORMAT_RGB32F:
  16934. return this._gl.RGB32F;
  16935. }
  16936. }
  16937. return this._gl.RGBA32F;
  16938. }
  16939. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16940. return this._gl.RGBA16F;
  16941. }
  16942. if (format) {
  16943. switch (format) {
  16944. case Engine.TEXTUREFORMAT_LUMINANCE:
  16945. return this._gl.LUMINANCE;
  16946. }
  16947. }
  16948. return this._gl.RGBA;
  16949. };
  16950. ;
  16951. /** @hidden */
  16952. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16953. if (type === Engine.TEXTURETYPE_FLOAT) {
  16954. return this._gl.RGBA32F;
  16955. }
  16956. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16957. return this._gl.RGBA16F;
  16958. }
  16959. return this._gl.RGBA8;
  16960. };
  16961. ;
  16962. /**
  16963. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16964. * @return the new query
  16965. */
  16966. Engine.prototype.createQuery = function () {
  16967. return this._gl.createQuery();
  16968. };
  16969. /**
  16970. * Delete and release a webGL query
  16971. * @param query defines the query to delete
  16972. * @return the current engine
  16973. */
  16974. Engine.prototype.deleteQuery = function (query) {
  16975. this._gl.deleteQuery(query);
  16976. return this;
  16977. };
  16978. /**
  16979. * Check if a given query has resolved and got its value
  16980. * @param query defines the query to check
  16981. * @returns true if the query got its value
  16982. */
  16983. Engine.prototype.isQueryResultAvailable = function (query) {
  16984. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16985. };
  16986. /**
  16987. * Gets the value of a given query
  16988. * @param query defines the query to check
  16989. * @returns the value of the query
  16990. */
  16991. Engine.prototype.getQueryResult = function (query) {
  16992. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16993. };
  16994. /**
  16995. * Initiates an occlusion query
  16996. * @param algorithmType defines the algorithm to use
  16997. * @param query defines the query to use
  16998. * @returns the current engine
  16999. * @see http://doc.babylonjs.com/features/occlusionquery
  17000. */
  17001. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17002. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17003. this._gl.beginQuery(glAlgorithm, query);
  17004. return this;
  17005. };
  17006. /**
  17007. * Ends an occlusion query
  17008. * @see http://doc.babylonjs.com/features/occlusionquery
  17009. * @param algorithmType defines the algorithm to use
  17010. * @returns the current engine
  17011. */
  17012. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17013. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17014. this._gl.endQuery(glAlgorithm);
  17015. return this;
  17016. };
  17017. /* Time queries */
  17018. Engine.prototype._createTimeQuery = function () {
  17019. var timerQuery = this._caps.timerQuery;
  17020. if (timerQuery.createQueryEXT) {
  17021. return timerQuery.createQueryEXT();
  17022. }
  17023. return this.createQuery();
  17024. };
  17025. Engine.prototype._deleteTimeQuery = function (query) {
  17026. var timerQuery = this._caps.timerQuery;
  17027. if (timerQuery.deleteQueryEXT) {
  17028. timerQuery.deleteQueryEXT(query);
  17029. return;
  17030. }
  17031. this.deleteQuery(query);
  17032. };
  17033. Engine.prototype._getTimeQueryResult = function (query) {
  17034. var timerQuery = this._caps.timerQuery;
  17035. if (timerQuery.getQueryObjectEXT) {
  17036. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17037. }
  17038. return this.getQueryResult(query);
  17039. };
  17040. Engine.prototype._getTimeQueryAvailability = function (query) {
  17041. var timerQuery = this._caps.timerQuery;
  17042. if (timerQuery.getQueryObjectEXT) {
  17043. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17044. }
  17045. return this.isQueryResultAvailable(query);
  17046. };
  17047. /**
  17048. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17049. * Please note that only one query can be issued at a time
  17050. * @returns a time token used to track the time span
  17051. */
  17052. Engine.prototype.startTimeQuery = function () {
  17053. var timerQuery = this._caps.timerQuery;
  17054. if (!timerQuery) {
  17055. return null;
  17056. }
  17057. var token = new BABYLON._TimeToken();
  17058. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17059. if (this._caps.canUseTimestampForTimerQuery) {
  17060. token._startTimeQuery = this._createTimeQuery();
  17061. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17062. }
  17063. else {
  17064. if (this._currentNonTimestampToken) {
  17065. return this._currentNonTimestampToken;
  17066. }
  17067. token._timeElapsedQuery = this._createTimeQuery();
  17068. if (timerQuery.beginQueryEXT) {
  17069. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17070. }
  17071. else {
  17072. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17073. }
  17074. this._currentNonTimestampToken = token;
  17075. }
  17076. return token;
  17077. };
  17078. /**
  17079. * Ends a time query
  17080. * @param token defines the token used to measure the time span
  17081. * @returns the time spent (in ns)
  17082. */
  17083. Engine.prototype.endTimeQuery = function (token) {
  17084. var timerQuery = this._caps.timerQuery;
  17085. if (!timerQuery || !token) {
  17086. return -1;
  17087. }
  17088. if (this._caps.canUseTimestampForTimerQuery) {
  17089. if (!token._startTimeQuery) {
  17090. return -1;
  17091. }
  17092. if (!token._endTimeQuery) {
  17093. token._endTimeQuery = this._createTimeQuery();
  17094. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17095. }
  17096. }
  17097. else if (!token._timeElapsedQueryEnded) {
  17098. if (!token._timeElapsedQuery) {
  17099. return -1;
  17100. }
  17101. if (timerQuery.endQueryEXT) {
  17102. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17103. }
  17104. else {
  17105. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17106. }
  17107. token._timeElapsedQueryEnded = true;
  17108. }
  17109. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17110. var available = false;
  17111. if (token._endTimeQuery) {
  17112. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17113. }
  17114. else if (token._timeElapsedQuery) {
  17115. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17116. }
  17117. if (available && !disjoint) {
  17118. var result = 0;
  17119. if (this._caps.canUseTimestampForTimerQuery) {
  17120. if (!token._startTimeQuery || !token._endTimeQuery) {
  17121. return -1;
  17122. }
  17123. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17124. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17125. result = timeEnd - timeStart;
  17126. this._deleteTimeQuery(token._startTimeQuery);
  17127. this._deleteTimeQuery(token._endTimeQuery);
  17128. token._startTimeQuery = null;
  17129. token._endTimeQuery = null;
  17130. }
  17131. else {
  17132. if (!token._timeElapsedQuery) {
  17133. return -1;
  17134. }
  17135. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17136. this._deleteTimeQuery(token._timeElapsedQuery);
  17137. token._timeElapsedQuery = null;
  17138. token._timeElapsedQueryEnded = false;
  17139. this._currentNonTimestampToken = null;
  17140. }
  17141. return result;
  17142. }
  17143. return -1;
  17144. };
  17145. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17146. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17147. };
  17148. // Transform feedback
  17149. /**
  17150. * Creates a webGL transform feedback object
  17151. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17152. * @returns the webGL transform feedback object
  17153. */
  17154. Engine.prototype.createTransformFeedback = function () {
  17155. return this._gl.createTransformFeedback();
  17156. };
  17157. /**
  17158. * Delete a webGL transform feedback object
  17159. * @param value defines the webGL transform feedback object to delete
  17160. */
  17161. Engine.prototype.deleteTransformFeedback = function (value) {
  17162. this._gl.deleteTransformFeedback(value);
  17163. };
  17164. /**
  17165. * Bind a webGL transform feedback object to the webgl context
  17166. * @param value defines the webGL transform feedback object to bind
  17167. */
  17168. Engine.prototype.bindTransformFeedback = function (value) {
  17169. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17170. };
  17171. /**
  17172. * Begins a transform feedback operation
  17173. * @param usePoints defines if points or triangles must be used
  17174. */
  17175. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17176. if (usePoints === void 0) { usePoints = true; }
  17177. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17178. };
  17179. /**
  17180. * Ends a transform feedback operation
  17181. */
  17182. Engine.prototype.endTransformFeedback = function () {
  17183. this._gl.endTransformFeedback();
  17184. };
  17185. /**
  17186. * Specify the varyings to use with transform feedback
  17187. * @param program defines the associated webGL program
  17188. * @param value defines the list of strings representing the varying names
  17189. */
  17190. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17191. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17192. };
  17193. /**
  17194. * Bind a webGL buffer for a transform feedback operation
  17195. * @param value defines the webGL buffer to bind
  17196. */
  17197. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17198. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17199. };
  17200. /** @hidden */
  17201. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17202. var _this = this;
  17203. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17204. this._activeRequests.push(request);
  17205. request.onCompleteObservable.add(function (request) {
  17206. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17207. });
  17208. return request;
  17209. };
  17210. /** @hidden */
  17211. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17212. var _this = this;
  17213. return new Promise(function (resolve, reject) {
  17214. _this._loadFile(url, function (data) {
  17215. resolve(data);
  17216. }, undefined, database, useArrayBuffer, function (request, exception) {
  17217. reject(exception);
  17218. });
  17219. });
  17220. };
  17221. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17222. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17223. var onload = function (data) {
  17224. loadedFiles[index] = data;
  17225. loadedFiles._internalCount++;
  17226. if (loadedFiles._internalCount === 6) {
  17227. onfinish(loadedFiles);
  17228. }
  17229. };
  17230. var onerror = function (request, exception) {
  17231. if (onErrorCallBack && request) {
  17232. onErrorCallBack(request.status + " " + request.statusText, exception);
  17233. }
  17234. };
  17235. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17236. };
  17237. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17238. if (onError === void 0) { onError = null; }
  17239. var loadedFiles = [];
  17240. loadedFiles._internalCount = 0;
  17241. for (var index = 0; index < 6; index++) {
  17242. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17243. }
  17244. };
  17245. // Statics
  17246. /**
  17247. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17248. * @returns true if the engine can be created
  17249. * @ignorenaming
  17250. */
  17251. Engine.isSupported = function () {
  17252. try {
  17253. var tempcanvas = document.createElement("canvas");
  17254. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17255. return gl != null && !!window.WebGLRenderingContext;
  17256. }
  17257. catch (e) {
  17258. return false;
  17259. }
  17260. };
  17261. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17262. Engine.ExceptionList = [
  17263. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17264. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17265. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17266. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17267. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17268. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17269. ];
  17270. /** Gets the list of created engines */
  17271. Engine.Instances = new Array();
  17272. // Const statics
  17273. Engine._ALPHA_DISABLE = 0;
  17274. Engine._ALPHA_ADD = 1;
  17275. Engine._ALPHA_COMBINE = 2;
  17276. Engine._ALPHA_SUBTRACT = 3;
  17277. Engine._ALPHA_MULTIPLY = 4;
  17278. Engine._ALPHA_MAXIMIZED = 5;
  17279. Engine._ALPHA_ONEONE = 6;
  17280. Engine._ALPHA_PREMULTIPLIED = 7;
  17281. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17282. Engine._ALPHA_INTERPOLATE = 9;
  17283. Engine._ALPHA_SCREENMODE = 10;
  17284. Engine._DELAYLOADSTATE_NONE = 0;
  17285. Engine._DELAYLOADSTATE_LOADED = 1;
  17286. Engine._DELAYLOADSTATE_LOADING = 2;
  17287. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17288. Engine._TEXTUREFORMAT_ALPHA = 0;
  17289. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17290. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17291. Engine._TEXTUREFORMAT_RGB = 4;
  17292. Engine._TEXTUREFORMAT_RGBA = 5;
  17293. Engine._TEXTUREFORMAT_R32F = 6;
  17294. Engine._TEXTUREFORMAT_RG32F = 7;
  17295. Engine._TEXTUREFORMAT_RGB32F = 8;
  17296. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17297. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17298. Engine._TEXTURETYPE_FLOAT = 1;
  17299. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17300. // Depht or Stencil test Constants.
  17301. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17302. Engine._ALWAYS = 0x0207; // 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.
  17303. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17304. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17305. Engine._LEQUAL = 0x0203; // 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.
  17306. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17307. Engine._GEQUAL = 0x0206; // 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.
  17308. Engine._NOTEQUAL = 0x0205; // 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.
  17309. // Stencil Actions Constants.
  17310. Engine._KEEP = 0x1E00;
  17311. Engine._REPLACE = 0x1E01;
  17312. Engine._INCR = 0x1E02;
  17313. Engine._DECR = 0x1E03;
  17314. Engine._INVERT = 0x150A;
  17315. Engine._INCR_WRAP = 0x8507;
  17316. Engine._DECR_WRAP = 0x8508;
  17317. // Texture rescaling mode
  17318. Engine._SCALEMODE_FLOOR = 1;
  17319. Engine._SCALEMODE_NEAREST = 2;
  17320. Engine._SCALEMODE_CEILING = 3;
  17321. // Updatable statics so stick with vars here
  17322. /**
  17323. * Gets or sets the epsilon value used by collision engine
  17324. */
  17325. Engine.CollisionsEpsilon = 0.001;
  17326. /**
  17327. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17328. */
  17329. Engine.CodeRepository = "src/";
  17330. /**
  17331. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17332. */
  17333. Engine.ShadersRepository = "src/Shaders/";
  17334. return Engine;
  17335. }());
  17336. BABYLON.Engine = Engine;
  17337. })(BABYLON || (BABYLON = {}));
  17338. //# sourceMappingURL=babylon.engine.js.map
  17339. var BABYLON;
  17340. (function (BABYLON) {
  17341. /**
  17342. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17343. */
  17344. var Node = /** @class */ (function () {
  17345. /**
  17346. * Creates a new Node
  17347. * @param {string} name - the name and id to be given to this node
  17348. * @param {BABYLON.Scene} the scene this node will be added to
  17349. */
  17350. function Node(name, scene) {
  17351. if (scene === void 0) { scene = null; }
  17352. /**
  17353. * Gets or sets a string used to store user defined state for the node
  17354. */
  17355. this.state = "";
  17356. /**
  17357. * Gets or sets an object used to store user defined information for the node
  17358. */
  17359. this.metadata = null;
  17360. /**
  17361. * Gets or sets a boolean used to define if the node must be serialized
  17362. */
  17363. this.doNotSerialize = false;
  17364. /** @hidden */
  17365. this._isDisposed = false;
  17366. /**
  17367. * Gets a list of Animations associated with the node
  17368. */
  17369. this.animations = new Array();
  17370. this._ranges = {};
  17371. this._isEnabled = true;
  17372. this._isReady = true;
  17373. /** @hidden */
  17374. this._currentRenderId = -1;
  17375. this._parentRenderId = -1;
  17376. this._childRenderId = -1;
  17377. this._animationPropertiesOverride = null;
  17378. /**
  17379. * An event triggered when the mesh is disposed
  17380. */
  17381. this.onDisposeObservable = new BABYLON.Observable();
  17382. // Behaviors
  17383. this._behaviors = new Array();
  17384. this.name = name;
  17385. this.id = name;
  17386. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17387. this.uniqueId = this._scene.getUniqueId();
  17388. this._initCache();
  17389. }
  17390. /**
  17391. * Gets a boolean indicating if the node has been disposed
  17392. * @returns true if the node was disposed
  17393. */
  17394. Node.prototype.isDisposed = function () {
  17395. return this._isDisposed;
  17396. };
  17397. Object.defineProperty(Node.prototype, "parent", {
  17398. get: function () {
  17399. return this._parentNode;
  17400. },
  17401. /**
  17402. * Gets or sets the parent of the node
  17403. */
  17404. set: function (parent) {
  17405. if (this._parentNode === parent) {
  17406. return;
  17407. }
  17408. // Remove self from list of children of parent
  17409. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17410. var index = this._parentNode._children.indexOf(this);
  17411. if (index !== -1) {
  17412. this._parentNode._children.splice(index, 1);
  17413. }
  17414. }
  17415. // Store new parent
  17416. this._parentNode = parent;
  17417. // Add as child to new parent
  17418. if (this._parentNode) {
  17419. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17420. this._parentNode._children = new Array();
  17421. }
  17422. this._parentNode._children.push(this);
  17423. }
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17429. /**
  17430. * Gets or sets the animation properties override
  17431. */
  17432. get: function () {
  17433. if (!this._animationPropertiesOverride) {
  17434. return this._scene.animationPropertiesOverride;
  17435. }
  17436. return this._animationPropertiesOverride;
  17437. },
  17438. set: function (value) {
  17439. this._animationPropertiesOverride = value;
  17440. },
  17441. enumerable: true,
  17442. configurable: true
  17443. });
  17444. /**
  17445. * Gets a string idenfifying the name of the class
  17446. * @returns "Node" string
  17447. */
  17448. Node.prototype.getClassName = function () {
  17449. return "Node";
  17450. };
  17451. Object.defineProperty(Node.prototype, "onDispose", {
  17452. /**
  17453. * Sets a callback that will be raised when the node will be disposed
  17454. */
  17455. set: function (callback) {
  17456. if (this._onDisposeObserver) {
  17457. this.onDisposeObservable.remove(this._onDisposeObserver);
  17458. }
  17459. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17460. },
  17461. enumerable: true,
  17462. configurable: true
  17463. });
  17464. /**
  17465. * Gets the scene of the node
  17466. * @returns a {BABYLON.Scene}
  17467. */
  17468. Node.prototype.getScene = function () {
  17469. return this._scene;
  17470. };
  17471. /**
  17472. * Gets the engine of the node
  17473. * @returns a {BABYLON.Engine}
  17474. */
  17475. Node.prototype.getEngine = function () {
  17476. return this._scene.getEngine();
  17477. };
  17478. /**
  17479. * Attach a behavior to the node
  17480. * @see http://doc.babylonjs.com/features/behaviour
  17481. * @param behavior defines the behavior to attach
  17482. * @returns the current Node
  17483. */
  17484. Node.prototype.addBehavior = function (behavior) {
  17485. var _this = this;
  17486. var index = this._behaviors.indexOf(behavior);
  17487. if (index !== -1) {
  17488. return this;
  17489. }
  17490. behavior.init();
  17491. if (this._scene.isLoading) {
  17492. // We defer the attach when the scene will be loaded
  17493. var observer = this._scene.onDataLoadedObservable.add(function () {
  17494. behavior.attach(_this);
  17495. setTimeout(function () {
  17496. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17497. _this._scene.onDataLoadedObservable.remove(observer);
  17498. }, 0);
  17499. });
  17500. }
  17501. else {
  17502. behavior.attach(this);
  17503. }
  17504. this._behaviors.push(behavior);
  17505. return this;
  17506. };
  17507. /**
  17508. * Remove an attached behavior
  17509. * @see http://doc.babylonjs.com/features/behaviour
  17510. * @param behavior defines the behavior to attach
  17511. * @returns the current Node
  17512. */
  17513. Node.prototype.removeBehavior = function (behavior) {
  17514. var index = this._behaviors.indexOf(behavior);
  17515. if (index === -1) {
  17516. return this;
  17517. }
  17518. this._behaviors[index].detach();
  17519. this._behaviors.splice(index, 1);
  17520. return this;
  17521. };
  17522. Object.defineProperty(Node.prototype, "behaviors", {
  17523. /**
  17524. * Gets the list of attached behaviors
  17525. * @see http://doc.babylonjs.com/features/behaviour
  17526. */
  17527. get: function () {
  17528. return this._behaviors;
  17529. },
  17530. enumerable: true,
  17531. configurable: true
  17532. });
  17533. /**
  17534. * Gets an attached behavior by name
  17535. * @param name defines the name of the behavior to look for
  17536. * @see http://doc.babylonjs.com/features/behaviour
  17537. * @returns null if behavior was not found else the requested behavior
  17538. */
  17539. Node.prototype.getBehaviorByName = function (name) {
  17540. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17541. var behavior = _a[_i];
  17542. if (behavior.name === name) {
  17543. return behavior;
  17544. }
  17545. }
  17546. return null;
  17547. };
  17548. /**
  17549. * Returns the world matrix of the node
  17550. * @returns a matrix containing the node's world matrix
  17551. */
  17552. Node.prototype.getWorldMatrix = function () {
  17553. return BABYLON.Matrix.Identity();
  17554. };
  17555. /** @hidden */
  17556. Node.prototype._getWorldMatrixDeterminant = function () {
  17557. return 1;
  17558. };
  17559. // override it in derived class if you add new variables to the cache
  17560. // and call the parent class method
  17561. /** @hidden */
  17562. Node.prototype._initCache = function () {
  17563. this._cache = {};
  17564. this._cache.parent = undefined;
  17565. };
  17566. /** @hidden */
  17567. Node.prototype.updateCache = function (force) {
  17568. if (!force && this.isSynchronized())
  17569. return;
  17570. this._cache.parent = this.parent;
  17571. this._updateCache();
  17572. };
  17573. // override it in derived class if you add new variables to the cache
  17574. // and call the parent class method if !ignoreParentClass
  17575. /** @hidden */
  17576. Node.prototype._updateCache = function (ignoreParentClass) {
  17577. };
  17578. // override it in derived class if you add new variables to the cache
  17579. /** @hidden */
  17580. Node.prototype._isSynchronized = function () {
  17581. return true;
  17582. };
  17583. /** @hidden */
  17584. Node.prototype._markSyncedWithParent = function () {
  17585. if (this.parent) {
  17586. this._parentRenderId = this.parent._childRenderId;
  17587. }
  17588. };
  17589. /** @hidden */
  17590. Node.prototype.isSynchronizedWithParent = function () {
  17591. if (!this.parent) {
  17592. return true;
  17593. }
  17594. if (this._parentRenderId !== this.parent._childRenderId) {
  17595. return false;
  17596. }
  17597. return this.parent.isSynchronized();
  17598. };
  17599. /** @hidden */
  17600. Node.prototype.isSynchronized = function (updateCache) {
  17601. var check = this.hasNewParent();
  17602. check = check || !this.isSynchronizedWithParent();
  17603. check = check || !this._isSynchronized();
  17604. if (updateCache)
  17605. this.updateCache(true);
  17606. return !check;
  17607. };
  17608. /** @hidden */
  17609. Node.prototype.hasNewParent = function (update) {
  17610. if (this._cache.parent === this.parent)
  17611. return false;
  17612. if (update)
  17613. this._cache.parent = this.parent;
  17614. return true;
  17615. };
  17616. /**
  17617. * Is this node ready to be used/rendered
  17618. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17619. * @return true if the node is ready
  17620. */
  17621. Node.prototype.isReady = function (completeCheck) {
  17622. if (completeCheck === void 0) { completeCheck = false; }
  17623. return this._isReady;
  17624. };
  17625. /**
  17626. * Is this node enabled?
  17627. * 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
  17628. * @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
  17629. * @return whether this node (and its parent) is enabled
  17630. */
  17631. Node.prototype.isEnabled = function (checkAncestors) {
  17632. if (checkAncestors === void 0) { checkAncestors = true; }
  17633. if (checkAncestors === false) {
  17634. return this._isEnabled;
  17635. }
  17636. if (this._isEnabled === false) {
  17637. return false;
  17638. }
  17639. if (this.parent !== undefined && this.parent !== null) {
  17640. return this.parent.isEnabled(checkAncestors);
  17641. }
  17642. return true;
  17643. };
  17644. /**
  17645. * Set the enabled state of this node
  17646. * @param value defines the new enabled state
  17647. */
  17648. Node.prototype.setEnabled = function (value) {
  17649. this._isEnabled = value;
  17650. };
  17651. /**
  17652. * Is this node a descendant of the given node?
  17653. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17654. * @param ancestor defines the parent node to inspect
  17655. * @returns a boolean indicating if this node is a descendant of the given node
  17656. */
  17657. Node.prototype.isDescendantOf = function (ancestor) {
  17658. if (this.parent) {
  17659. if (this.parent === ancestor) {
  17660. return true;
  17661. }
  17662. return this.parent.isDescendantOf(ancestor);
  17663. }
  17664. return false;
  17665. };
  17666. /** @hidden */
  17667. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17668. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17669. if (!this._children) {
  17670. return;
  17671. }
  17672. for (var index = 0; index < this._children.length; index++) {
  17673. var item = this._children[index];
  17674. if (!predicate || predicate(item)) {
  17675. results.push(item);
  17676. }
  17677. if (!directDescendantsOnly) {
  17678. item._getDescendants(results, false, predicate);
  17679. }
  17680. }
  17681. };
  17682. /**
  17683. * Will return all nodes that have this node as ascendant
  17684. * @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
  17685. * @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
  17686. * @return all children nodes of all types
  17687. */
  17688. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17689. var results = new Array();
  17690. this._getDescendants(results, directDescendantsOnly, predicate);
  17691. return results;
  17692. };
  17693. /**
  17694. * Get all child-meshes of this node
  17695. * @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
  17696. * @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
  17697. * @returns an array of {BABYLON.AbstractMesh}
  17698. */
  17699. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17700. var results = [];
  17701. this._getDescendants(results, directDescendantsOnly, function (node) {
  17702. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17703. });
  17704. return results;
  17705. };
  17706. /**
  17707. * Get all child-transformNodes of this node
  17708. * @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
  17709. * @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
  17710. * @returns an array of {BABYLON.TransformNode}
  17711. */
  17712. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17713. var results = [];
  17714. this._getDescendants(results, directDescendantsOnly, function (node) {
  17715. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17716. });
  17717. return results;
  17718. };
  17719. /**
  17720. * Get all direct children of this node
  17721. * @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
  17722. * @returns an array of {BABYLON.Node}
  17723. */
  17724. Node.prototype.getChildren = function (predicate) {
  17725. return this.getDescendants(true, predicate);
  17726. };
  17727. /** @hidden */
  17728. Node.prototype._setReady = function (state) {
  17729. if (state === this._isReady) {
  17730. return;
  17731. }
  17732. if (!state) {
  17733. this._isReady = false;
  17734. return;
  17735. }
  17736. if (this.onReady) {
  17737. this.onReady(this);
  17738. }
  17739. this._isReady = true;
  17740. };
  17741. /**
  17742. * Get an animation by name
  17743. * @param name defines the name of the animation to look for
  17744. * @returns null if not found else the requested animation
  17745. */
  17746. Node.prototype.getAnimationByName = function (name) {
  17747. for (var i = 0; i < this.animations.length; i++) {
  17748. var animation = this.animations[i];
  17749. if (animation.name === name) {
  17750. return animation;
  17751. }
  17752. }
  17753. return null;
  17754. };
  17755. /**
  17756. * Creates an animation range for this node
  17757. * @param name defines the name of the range
  17758. * @param from defines the starting key
  17759. * @param to defines the end key
  17760. */
  17761. Node.prototype.createAnimationRange = function (name, from, to) {
  17762. // check name not already in use
  17763. if (!this._ranges[name]) {
  17764. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17765. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17766. if (this.animations[i]) {
  17767. this.animations[i].createRange(name, from, to);
  17768. }
  17769. }
  17770. }
  17771. };
  17772. /**
  17773. * Delete a specific animation range
  17774. * @param name defines the name of the range to delete
  17775. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17776. */
  17777. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17778. if (deleteFrames === void 0) { deleteFrames = true; }
  17779. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17780. if (this.animations[i]) {
  17781. this.animations[i].deleteRange(name, deleteFrames);
  17782. }
  17783. }
  17784. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17785. };
  17786. /**
  17787. * Get an animation range by name
  17788. * @param name defines the name of the animation range to look for
  17789. * @returns null if not found else the requested animation range
  17790. */
  17791. Node.prototype.getAnimationRange = function (name) {
  17792. return this._ranges[name];
  17793. };
  17794. /**
  17795. * Will start the animation sequence
  17796. * @param name defines the range frames for animation sequence
  17797. * @param loop defines if the animation should loop (false by default)
  17798. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17799. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17800. * @returns the object created for this animation. If range does not exist, it will return null
  17801. */
  17802. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17803. var range = this.getAnimationRange(name);
  17804. if (!range) {
  17805. return null;
  17806. }
  17807. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17808. };
  17809. /**
  17810. * Serialize animation ranges into a JSON compatible object
  17811. * @returns serialization object
  17812. */
  17813. Node.prototype.serializeAnimationRanges = function () {
  17814. var serializationRanges = [];
  17815. for (var name in this._ranges) {
  17816. var localRange = this._ranges[name];
  17817. if (!localRange) {
  17818. continue;
  17819. }
  17820. var range = {};
  17821. range.name = name;
  17822. range.from = localRange.from;
  17823. range.to = localRange.to;
  17824. serializationRanges.push(range);
  17825. }
  17826. return serializationRanges;
  17827. };
  17828. /**
  17829. * Computes the world matrix of the node
  17830. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17831. * @returns the world matrix
  17832. */
  17833. Node.prototype.computeWorldMatrix = function (force) {
  17834. return BABYLON.Matrix.Identity();
  17835. };
  17836. /**
  17837. * Releases resources associated with this node.
  17838. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17839. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17840. */
  17841. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17842. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17843. if (!doNotRecurse) {
  17844. var nodes = this.getDescendants(true);
  17845. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17846. var node = nodes_1[_i];
  17847. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17848. }
  17849. }
  17850. else {
  17851. var transformNodes = this.getChildTransformNodes(true);
  17852. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17853. var transformNode = transformNodes_1[_a];
  17854. transformNode.parent = null;
  17855. transformNode.computeWorldMatrix(true);
  17856. }
  17857. }
  17858. this.parent = null;
  17859. // Callback
  17860. this.onDisposeObservable.notifyObservers(this);
  17861. this.onDisposeObservable.clear();
  17862. // Behaviors
  17863. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17864. var behavior = _c[_b];
  17865. behavior.detach();
  17866. }
  17867. this._behaviors = [];
  17868. this._isDisposed = true;
  17869. };
  17870. /**
  17871. * Parse animation range data from a serialization object and store them into a given node
  17872. * @param node defines where to store the animation ranges
  17873. * @param parsedNode defines the serialization object to read data from
  17874. * @param scene defines the hosting scene
  17875. */
  17876. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17877. if (parsedNode.ranges) {
  17878. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17879. var data = parsedNode.ranges[index];
  17880. node.createAnimationRange(data.name, data.from, data.to);
  17881. }
  17882. }
  17883. };
  17884. __decorate([
  17885. BABYLON.serialize()
  17886. ], Node.prototype, "name", void 0);
  17887. __decorate([
  17888. BABYLON.serialize()
  17889. ], Node.prototype, "id", void 0);
  17890. __decorate([
  17891. BABYLON.serialize()
  17892. ], Node.prototype, "uniqueId", void 0);
  17893. __decorate([
  17894. BABYLON.serialize()
  17895. ], Node.prototype, "state", void 0);
  17896. __decorate([
  17897. BABYLON.serialize()
  17898. ], Node.prototype, "metadata", void 0);
  17899. return Node;
  17900. }());
  17901. BABYLON.Node = Node;
  17902. })(BABYLON || (BABYLON = {}));
  17903. //# sourceMappingURL=babylon.node.js.map
  17904. var BABYLON;
  17905. (function (BABYLON) {
  17906. var BoundingSphere = /** @class */ (function () {
  17907. /**
  17908. * Creates a new bounding sphere
  17909. * @param min defines the minimum vector (in local space)
  17910. * @param max defines the maximum vector (in local space)
  17911. */
  17912. function BoundingSphere(min, max) {
  17913. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17914. this.reConstruct(min, max);
  17915. }
  17916. /**
  17917. * Recreates the entire bounding sphere from scratch
  17918. * @param min defines the new minimum vector (in local space)
  17919. * @param max defines the new maximum vector (in local space)
  17920. */
  17921. BoundingSphere.prototype.reConstruct = function (min, max) {
  17922. this.minimum = min.clone();
  17923. this.maximum = max.clone();
  17924. var distance = BABYLON.Vector3.Distance(min, max);
  17925. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17926. this.radius = distance * 0.5;
  17927. this.centerWorld = BABYLON.Vector3.Zero();
  17928. this._update(BABYLON.Matrix.Identity());
  17929. };
  17930. // Methods
  17931. BoundingSphere.prototype._update = function (world) {
  17932. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17933. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17934. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17935. };
  17936. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17937. for (var i = 0; i < 6; i++) {
  17938. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17939. return false;
  17940. }
  17941. return true;
  17942. };
  17943. BoundingSphere.prototype.intersectsPoint = function (point) {
  17944. var x = this.centerWorld.x - point.x;
  17945. var y = this.centerWorld.y - point.y;
  17946. var z = this.centerWorld.z - point.z;
  17947. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17948. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17949. return false;
  17950. return true;
  17951. };
  17952. // Statics
  17953. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17954. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17955. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17956. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17957. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17958. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17959. return false;
  17960. return true;
  17961. };
  17962. return BoundingSphere;
  17963. }());
  17964. BABYLON.BoundingSphere = BoundingSphere;
  17965. })(BABYLON || (BABYLON = {}));
  17966. //# sourceMappingURL=babylon.boundingSphere.js.map
  17967. var BABYLON;
  17968. (function (BABYLON) {
  17969. var BoundingBox = /** @class */ (function () {
  17970. /**
  17971. * Creates a new bounding box
  17972. * @param min defines the minimum vector (in local space)
  17973. * @param max defines the maximum vector (in local space)
  17974. */
  17975. function BoundingBox(min, max) {
  17976. this.vectorsWorld = new Array();
  17977. this.reConstruct(min, max);
  17978. }
  17979. // Methods
  17980. /**
  17981. * Recreates the entire bounding box from scratch
  17982. * @param min defines the new minimum vector (in local space)
  17983. * @param max defines the new maximum vector (in local space)
  17984. */
  17985. BoundingBox.prototype.reConstruct = function (min, max) {
  17986. this.minimum = min.clone();
  17987. this.maximum = max.clone();
  17988. // Bounding vectors
  17989. this.vectors = new Array();
  17990. this.vectors.push(this.minimum.clone());
  17991. this.vectors.push(this.maximum.clone());
  17992. this.vectors.push(this.minimum.clone());
  17993. this.vectors[2].x = this.maximum.x;
  17994. this.vectors.push(this.minimum.clone());
  17995. this.vectors[3].y = this.maximum.y;
  17996. this.vectors.push(this.minimum.clone());
  17997. this.vectors[4].z = this.maximum.z;
  17998. this.vectors.push(this.maximum.clone());
  17999. this.vectors[5].z = this.minimum.z;
  18000. this.vectors.push(this.maximum.clone());
  18001. this.vectors[6].x = this.minimum.x;
  18002. this.vectors.push(this.maximum.clone());
  18003. this.vectors[7].y = this.minimum.y;
  18004. // OBB
  18005. this.center = this.maximum.add(this.minimum).scale(0.5);
  18006. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18007. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18008. // World
  18009. for (var index = 0; index < this.vectors.length; index++) {
  18010. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18011. }
  18012. this.minimumWorld = BABYLON.Vector3.Zero();
  18013. this.maximumWorld = BABYLON.Vector3.Zero();
  18014. this.centerWorld = BABYLON.Vector3.Zero();
  18015. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18016. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18017. };
  18018. BoundingBox.prototype.getWorldMatrix = function () {
  18019. return this._worldMatrix;
  18020. };
  18021. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18022. this._worldMatrix.copyFrom(matrix);
  18023. return this;
  18024. };
  18025. BoundingBox.prototype._update = function (world) {
  18026. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18027. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18028. for (var index = 0; index < this.vectors.length; index++) {
  18029. var v = this.vectorsWorld[index];
  18030. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18031. if (v.x < this.minimumWorld.x)
  18032. this.minimumWorld.x = v.x;
  18033. if (v.y < this.minimumWorld.y)
  18034. this.minimumWorld.y = v.y;
  18035. if (v.z < this.minimumWorld.z)
  18036. this.minimumWorld.z = v.z;
  18037. if (v.x > this.maximumWorld.x)
  18038. this.maximumWorld.x = v.x;
  18039. if (v.y > this.maximumWorld.y)
  18040. this.maximumWorld.y = v.y;
  18041. if (v.z > this.maximumWorld.z)
  18042. this.maximumWorld.z = v.z;
  18043. }
  18044. // Extend
  18045. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18046. this.extendSizeWorld.scaleInPlace(0.5);
  18047. // OBB
  18048. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18049. this.centerWorld.scaleInPlace(0.5);
  18050. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18051. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18052. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18053. this._worldMatrix = world;
  18054. };
  18055. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18056. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18057. };
  18058. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18059. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18060. };
  18061. BoundingBox.prototype.intersectsPoint = function (point) {
  18062. var delta = -BABYLON.Epsilon;
  18063. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18064. return false;
  18065. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18066. return false;
  18067. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18068. return false;
  18069. return true;
  18070. };
  18071. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18072. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18073. };
  18074. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18075. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18076. return false;
  18077. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18078. return false;
  18079. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18080. return false;
  18081. return true;
  18082. };
  18083. // Statics
  18084. BoundingBox.Intersects = function (box0, box1) {
  18085. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18086. return false;
  18087. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18088. return false;
  18089. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18090. return false;
  18091. return true;
  18092. };
  18093. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18094. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18095. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18096. return (num <= (sphereRadius * sphereRadius));
  18097. };
  18098. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18099. for (var p = 0; p < 6; p++) {
  18100. for (var i = 0; i < 8; i++) {
  18101. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18102. return false;
  18103. }
  18104. }
  18105. }
  18106. return true;
  18107. };
  18108. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18109. for (var p = 0; p < 6; p++) {
  18110. var inCount = 8;
  18111. for (var i = 0; i < 8; i++) {
  18112. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18113. --inCount;
  18114. }
  18115. else {
  18116. break;
  18117. }
  18118. }
  18119. if (inCount === 0)
  18120. return false;
  18121. }
  18122. return true;
  18123. };
  18124. return BoundingBox;
  18125. }());
  18126. BABYLON.BoundingBox = BoundingBox;
  18127. })(BABYLON || (BABYLON = {}));
  18128. //# sourceMappingURL=babylon.boundingBox.js.map
  18129. var BABYLON;
  18130. (function (BABYLON) {
  18131. var computeBoxExtents = function (axis, box) {
  18132. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18133. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18134. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18135. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18136. var r = r0 + r1 + r2;
  18137. return {
  18138. min: p - r,
  18139. max: p + r
  18140. };
  18141. };
  18142. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18143. var axisOverlap = function (axis, box0, box1) {
  18144. var result0 = computeBoxExtents(axis, box0);
  18145. var result1 = computeBoxExtents(axis, box1);
  18146. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18147. };
  18148. var BoundingInfo = /** @class */ (function () {
  18149. function BoundingInfo(minimum, maximum) {
  18150. this.minimum = minimum;
  18151. this.maximum = maximum;
  18152. this._isLocked = false;
  18153. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18154. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18155. }
  18156. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18157. get: function () {
  18158. return this._isLocked;
  18159. },
  18160. set: function (value) {
  18161. this._isLocked = value;
  18162. },
  18163. enumerable: true,
  18164. configurable: true
  18165. });
  18166. // Methods
  18167. BoundingInfo.prototype.update = function (world) {
  18168. if (this._isLocked) {
  18169. return;
  18170. }
  18171. this.boundingBox._update(world);
  18172. this.boundingSphere._update(world);
  18173. };
  18174. /**
  18175. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18176. * @param center New center of the bounding info
  18177. * @param extend New extend of the bounding info
  18178. */
  18179. BoundingInfo.prototype.centerOn = function (center, extend) {
  18180. this.minimum = center.subtract(extend);
  18181. this.maximum = center.add(extend);
  18182. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18183. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18184. return this;
  18185. };
  18186. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18187. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18188. return false;
  18189. return this.boundingBox.isInFrustum(frustumPlanes);
  18190. };
  18191. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18192. /**
  18193. * Gets the world distance between the min and max points of the bounding box
  18194. */
  18195. get: function () {
  18196. var boundingBox = this.boundingBox;
  18197. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18198. return size.length();
  18199. },
  18200. enumerable: true,
  18201. configurable: true
  18202. });
  18203. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18204. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18205. };
  18206. BoundingInfo.prototype._checkCollision = function (collider) {
  18207. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18208. };
  18209. BoundingInfo.prototype.intersectsPoint = function (point) {
  18210. if (!this.boundingSphere.centerWorld) {
  18211. return false;
  18212. }
  18213. if (!this.boundingSphere.intersectsPoint(point)) {
  18214. return false;
  18215. }
  18216. if (!this.boundingBox.intersectsPoint(point)) {
  18217. return false;
  18218. }
  18219. return true;
  18220. };
  18221. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18222. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18223. return false;
  18224. }
  18225. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18226. return false;
  18227. }
  18228. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18229. return false;
  18230. }
  18231. if (!precise) {
  18232. return true;
  18233. }
  18234. var box0 = this.boundingBox;
  18235. var box1 = boundingInfo.boundingBox;
  18236. if (!axisOverlap(box0.directions[0], box0, box1))
  18237. return false;
  18238. if (!axisOverlap(box0.directions[1], box0, box1))
  18239. return false;
  18240. if (!axisOverlap(box0.directions[2], box0, box1))
  18241. return false;
  18242. if (!axisOverlap(box1.directions[0], box0, box1))
  18243. return false;
  18244. if (!axisOverlap(box1.directions[1], box0, box1))
  18245. return false;
  18246. if (!axisOverlap(box1.directions[2], box0, box1))
  18247. return false;
  18248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18249. return false;
  18250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18251. return false;
  18252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18253. return false;
  18254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18255. return false;
  18256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18257. return false;
  18258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18259. return false;
  18260. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18261. return false;
  18262. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18263. return false;
  18264. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18265. return false;
  18266. return true;
  18267. };
  18268. return BoundingInfo;
  18269. }());
  18270. BABYLON.BoundingInfo = BoundingInfo;
  18271. })(BABYLON || (BABYLON = {}));
  18272. //# sourceMappingURL=babylon.boundingInfo.js.map
  18273. var BABYLON;
  18274. (function (BABYLON) {
  18275. var TransformNode = /** @class */ (function (_super) {
  18276. __extends(TransformNode, _super);
  18277. function TransformNode(name, scene, isPure) {
  18278. if (scene === void 0) { scene = null; }
  18279. if (isPure === void 0) { isPure = true; }
  18280. var _this = _super.call(this, name, scene) || this;
  18281. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18282. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18283. _this._up = new BABYLON.Vector3(0, 1, 0);
  18284. _this._right = new BABYLON.Vector3(1, 0, 0);
  18285. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18286. // Properties
  18287. _this._rotation = BABYLON.Vector3.Zero();
  18288. _this._scaling = BABYLON.Vector3.One();
  18289. _this._isDirty = false;
  18290. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18291. _this.scalingDeterminant = 1;
  18292. _this.infiniteDistance = false;
  18293. _this.position = BABYLON.Vector3.Zero();
  18294. _this._localWorld = BABYLON.Matrix.Zero();
  18295. _this._worldMatrix = BABYLON.Matrix.Zero();
  18296. _this._worldMatrixDeterminant = 0;
  18297. _this._absolutePosition = BABYLON.Vector3.Zero();
  18298. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18299. _this._postMultiplyPivotMatrix = false;
  18300. _this._isWorldMatrixFrozen = false;
  18301. /**
  18302. * An event triggered after the world matrix is updated
  18303. */
  18304. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18305. _this._nonUniformScaling = false;
  18306. if (isPure) {
  18307. _this.getScene().addTransformNode(_this);
  18308. }
  18309. return _this;
  18310. }
  18311. /**
  18312. * Gets a string idenfifying the name of the class
  18313. * @returns "TransformNode" string
  18314. */
  18315. TransformNode.prototype.getClassName = function () {
  18316. return "TransformNode";
  18317. };
  18318. Object.defineProperty(TransformNode.prototype, "rotation", {
  18319. /**
  18320. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18321. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18322. * Default : (0.0, 0.0, 0.0)
  18323. */
  18324. get: function () {
  18325. return this._rotation;
  18326. },
  18327. set: function (newRotation) {
  18328. this._rotation = newRotation;
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(TransformNode.prototype, "scaling", {
  18334. /**
  18335. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18336. * Default : (1.0, 1.0, 1.0)
  18337. */
  18338. get: function () {
  18339. return this._scaling;
  18340. },
  18341. /**
  18342. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18343. * Default : (1.0, 1.0, 1.0)
  18344. */
  18345. set: function (newScaling) {
  18346. this._scaling = newScaling;
  18347. },
  18348. enumerable: true,
  18349. configurable: true
  18350. });
  18351. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18352. /**
  18353. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18354. * It's null by default.
  18355. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18356. */
  18357. get: function () {
  18358. return this._rotationQuaternion;
  18359. },
  18360. set: function (quaternion) {
  18361. this._rotationQuaternion = quaternion;
  18362. //reset the rotation vector.
  18363. if (quaternion && this.rotation.length()) {
  18364. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18365. }
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(TransformNode.prototype, "forward", {
  18371. /**
  18372. * The forward direction of that transform in world space.
  18373. */
  18374. get: function () {
  18375. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18376. },
  18377. enumerable: true,
  18378. configurable: true
  18379. });
  18380. Object.defineProperty(TransformNode.prototype, "up", {
  18381. /**
  18382. * The up direction of that transform in world space.
  18383. */
  18384. get: function () {
  18385. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18386. },
  18387. enumerable: true,
  18388. configurable: true
  18389. });
  18390. Object.defineProperty(TransformNode.prototype, "right", {
  18391. /**
  18392. * The right direction of that transform in world space.
  18393. */
  18394. get: function () {
  18395. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18396. },
  18397. enumerable: true,
  18398. configurable: true
  18399. });
  18400. /**
  18401. * Returns the latest update of the World matrix
  18402. * Returns a Matrix.
  18403. */
  18404. TransformNode.prototype.getWorldMatrix = function () {
  18405. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18406. this.computeWorldMatrix();
  18407. }
  18408. return this._worldMatrix;
  18409. };
  18410. /** @hidden */
  18411. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18412. return this._worldMatrixDeterminant;
  18413. };
  18414. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18415. /**
  18416. * Returns directly the latest state of the mesh World matrix.
  18417. * A Matrix is returned.
  18418. */
  18419. get: function () {
  18420. return this._worldMatrix;
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. /**
  18426. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18427. * Returns the TransformNode.
  18428. */
  18429. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18430. this._poseMatrix.copyFrom(matrix);
  18431. return this;
  18432. };
  18433. /**
  18434. * Returns the mesh Pose matrix.
  18435. * Returned object : Matrix
  18436. */
  18437. TransformNode.prototype.getPoseMatrix = function () {
  18438. return this._poseMatrix;
  18439. };
  18440. TransformNode.prototype._isSynchronized = function () {
  18441. if (this._isDirty) {
  18442. return false;
  18443. }
  18444. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18445. return false;
  18446. if (this._cache.pivotMatrixUpdated) {
  18447. return false;
  18448. }
  18449. if (this.infiniteDistance) {
  18450. return false;
  18451. }
  18452. if (!this._cache.position.equals(this.position))
  18453. return false;
  18454. if (this.rotationQuaternion) {
  18455. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18456. return false;
  18457. }
  18458. if (!this._cache.rotation.equals(this.rotation))
  18459. return false;
  18460. if (!this._cache.scaling.equals(this.scaling))
  18461. return false;
  18462. return true;
  18463. };
  18464. TransformNode.prototype._initCache = function () {
  18465. _super.prototype._initCache.call(this);
  18466. this._cache.localMatrixUpdated = false;
  18467. this._cache.position = BABYLON.Vector3.Zero();
  18468. this._cache.scaling = BABYLON.Vector3.Zero();
  18469. this._cache.rotation = BABYLON.Vector3.Zero();
  18470. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18471. this._cache.billboardMode = -1;
  18472. };
  18473. TransformNode.prototype.markAsDirty = function (property) {
  18474. if (property === "rotation") {
  18475. this.rotationQuaternion = null;
  18476. }
  18477. this._currentRenderId = Number.MAX_VALUE;
  18478. this._isDirty = true;
  18479. return this;
  18480. };
  18481. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18482. /**
  18483. * Returns the current mesh absolute position.
  18484. * Retuns a Vector3.
  18485. */
  18486. get: function () {
  18487. return this._absolutePosition;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. /**
  18493. * Sets a new matrix to apply before all other transformation
  18494. * @param matrix defines the transform matrix
  18495. * @returns the current TransformNode
  18496. */
  18497. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18498. return this.setPivotMatrix(matrix, false);
  18499. };
  18500. /**
  18501. * Sets a new pivot matrix to the current node
  18502. * @param matrix defines the new pivot matrix to use
  18503. * @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
  18504. * @returns the current TransformNode
  18505. */
  18506. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18507. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18508. this._pivotMatrix = matrix.clone();
  18509. this._cache.pivotMatrixUpdated = true;
  18510. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18511. if (this._postMultiplyPivotMatrix) {
  18512. if (!this._pivotMatrixInverse) {
  18513. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18514. }
  18515. else {
  18516. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18517. }
  18518. }
  18519. return this;
  18520. };
  18521. /**
  18522. * Returns the mesh pivot matrix.
  18523. * Default : Identity.
  18524. * A Matrix is returned.
  18525. */
  18526. TransformNode.prototype.getPivotMatrix = function () {
  18527. return this._pivotMatrix;
  18528. };
  18529. /**
  18530. * Prevents the World matrix to be computed any longer.
  18531. * Returns the TransformNode.
  18532. */
  18533. TransformNode.prototype.freezeWorldMatrix = function () {
  18534. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18535. this.computeWorldMatrix(true);
  18536. this._isWorldMatrixFrozen = true;
  18537. return this;
  18538. };
  18539. /**
  18540. * Allows back the World matrix computation.
  18541. * Returns the TransformNode.
  18542. */
  18543. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18544. this._isWorldMatrixFrozen = false;
  18545. this.computeWorldMatrix(true);
  18546. return this;
  18547. };
  18548. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18549. /**
  18550. * True if the World matrix has been frozen.
  18551. * Returns a boolean.
  18552. */
  18553. get: function () {
  18554. return this._isWorldMatrixFrozen;
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. /**
  18560. * Retuns the mesh absolute position in the World.
  18561. * Returns a Vector3.
  18562. */
  18563. TransformNode.prototype.getAbsolutePosition = function () {
  18564. this.computeWorldMatrix();
  18565. return this._absolutePosition;
  18566. };
  18567. /**
  18568. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18569. * Returns the TransformNode.
  18570. */
  18571. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18572. if (!absolutePosition) {
  18573. return this;
  18574. }
  18575. var absolutePositionX;
  18576. var absolutePositionY;
  18577. var absolutePositionZ;
  18578. if (absolutePosition.x === undefined) {
  18579. if (arguments.length < 3) {
  18580. return this;
  18581. }
  18582. absolutePositionX = arguments[0];
  18583. absolutePositionY = arguments[1];
  18584. absolutePositionZ = arguments[2];
  18585. }
  18586. else {
  18587. absolutePositionX = absolutePosition.x;
  18588. absolutePositionY = absolutePosition.y;
  18589. absolutePositionZ = absolutePosition.z;
  18590. }
  18591. if (this.parent) {
  18592. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18593. invertParentWorldMatrix.invert();
  18594. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18595. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18596. }
  18597. else {
  18598. this.position.x = absolutePositionX;
  18599. this.position.y = absolutePositionY;
  18600. this.position.z = absolutePositionZ;
  18601. }
  18602. return this;
  18603. };
  18604. /**
  18605. * Sets the mesh position in its local space.
  18606. * Returns the TransformNode.
  18607. */
  18608. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18609. this.computeWorldMatrix();
  18610. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18611. return this;
  18612. };
  18613. /**
  18614. * Returns the mesh position in the local space from the current World matrix values.
  18615. * Returns a new Vector3.
  18616. */
  18617. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18618. this.computeWorldMatrix();
  18619. var invLocalWorldMatrix = this._localWorld.clone();
  18620. invLocalWorldMatrix.invert();
  18621. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18622. };
  18623. /**
  18624. * Translates the mesh along the passed Vector3 in its local space.
  18625. * Returns the TransformNode.
  18626. */
  18627. TransformNode.prototype.locallyTranslate = function (vector3) {
  18628. this.computeWorldMatrix(true);
  18629. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18630. return this;
  18631. };
  18632. /**
  18633. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18634. * @param targetPoint the position (must be in same space as current mesh) to look at
  18635. * @param yawCor optional yaw (y-axis) correction in radians
  18636. * @param pitchCor optional pitch (x-axis) correction in radians
  18637. * @param rollCor optional roll (z-axis) correction in radians
  18638. * @param space the choosen space of the target
  18639. * @returns the TransformNode.
  18640. */
  18641. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18642. if (yawCor === void 0) { yawCor = 0; }
  18643. if (pitchCor === void 0) { pitchCor = 0; }
  18644. if (rollCor === void 0) { rollCor = 0; }
  18645. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18646. var dv = TransformNode._lookAtVectorCache;
  18647. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18648. targetPoint.subtractToRef(pos, dv);
  18649. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18650. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18651. var pitch = Math.atan2(dv.y, len);
  18652. if (this.rotationQuaternion) {
  18653. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18654. }
  18655. else {
  18656. this.rotation.x = pitch + pitchCor;
  18657. this.rotation.y = yaw + yawCor;
  18658. this.rotation.z = rollCor;
  18659. }
  18660. return this;
  18661. };
  18662. /**
  18663. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18664. * This Vector3 is expressed in the World space.
  18665. */
  18666. TransformNode.prototype.getDirection = function (localAxis) {
  18667. var result = BABYLON.Vector3.Zero();
  18668. this.getDirectionToRef(localAxis, result);
  18669. return result;
  18670. };
  18671. /**
  18672. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18673. * localAxis is expressed in the mesh local space.
  18674. * result is computed in the Wordl space from the mesh World matrix.
  18675. * Returns the TransformNode.
  18676. */
  18677. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18678. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18679. return this;
  18680. };
  18681. /**
  18682. * Sets a new pivot point to the current node
  18683. * @param point defines the new pivot point to use
  18684. * @param space defines if the point is in world or local space (local by default)
  18685. * @returns the current TransformNode
  18686. */
  18687. TransformNode.prototype.setPivotPoint = function (point, space) {
  18688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18689. if (this.getScene().getRenderId() == 0) {
  18690. this.computeWorldMatrix(true);
  18691. }
  18692. var wm = this.getWorldMatrix();
  18693. if (space == BABYLON.Space.WORLD) {
  18694. var tmat = BABYLON.Tmp.Matrix[0];
  18695. wm.invertToRef(tmat);
  18696. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18697. }
  18698. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18699. };
  18700. /**
  18701. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18702. */
  18703. TransformNode.prototype.getPivotPoint = function () {
  18704. var point = BABYLON.Vector3.Zero();
  18705. this.getPivotPointToRef(point);
  18706. return point;
  18707. };
  18708. /**
  18709. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18710. * Returns the TransformNode.
  18711. */
  18712. TransformNode.prototype.getPivotPointToRef = function (result) {
  18713. result.x = -this._pivotMatrix.m[12];
  18714. result.y = -this._pivotMatrix.m[13];
  18715. result.z = -this._pivotMatrix.m[14];
  18716. return this;
  18717. };
  18718. /**
  18719. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18720. */
  18721. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18722. var point = BABYLON.Vector3.Zero();
  18723. this.getAbsolutePivotPointToRef(point);
  18724. return point;
  18725. };
  18726. /**
  18727. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18731. result.x = this._pivotMatrix.m[12];
  18732. result.y = this._pivotMatrix.m[13];
  18733. result.z = this._pivotMatrix.m[14];
  18734. this.getPivotPointToRef(result);
  18735. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18736. return this;
  18737. };
  18738. /**
  18739. * Defines the passed node as the parent of the current node.
  18740. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18741. * Returns the TransformNode.
  18742. */
  18743. TransformNode.prototype.setParent = function (node) {
  18744. if (node === null) {
  18745. var rotation = BABYLON.Tmp.Quaternion[0];
  18746. var position = BABYLON.Tmp.Vector3[0];
  18747. var scale = BABYLON.Tmp.Vector3[1];
  18748. if (this.parent && this.parent.computeWorldMatrix) {
  18749. this.parent.computeWorldMatrix(true);
  18750. }
  18751. this.computeWorldMatrix(true);
  18752. this.getWorldMatrix().decompose(scale, rotation, position);
  18753. if (this.rotationQuaternion) {
  18754. this.rotationQuaternion.copyFrom(rotation);
  18755. }
  18756. else {
  18757. rotation.toEulerAnglesToRef(this.rotation);
  18758. }
  18759. this.scaling.x = scale.x;
  18760. this.scaling.y = scale.y;
  18761. this.scaling.z = scale.z;
  18762. this.position.x = position.x;
  18763. this.position.y = position.y;
  18764. this.position.z = position.z;
  18765. }
  18766. else {
  18767. var rotation = BABYLON.Tmp.Quaternion[0];
  18768. var position = BABYLON.Tmp.Vector3[0];
  18769. var scale = BABYLON.Tmp.Vector3[1];
  18770. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18771. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18772. this.computeWorldMatrix(true);
  18773. node.computeWorldMatrix(true);
  18774. node.getWorldMatrix().invertToRef(invParentMatrix);
  18775. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18776. diffMatrix.decompose(scale, rotation, position);
  18777. if (this.rotationQuaternion) {
  18778. this.rotationQuaternion.copyFrom(rotation);
  18779. }
  18780. else {
  18781. rotation.toEulerAnglesToRef(this.rotation);
  18782. }
  18783. this.position.x = position.x;
  18784. this.position.y = position.y;
  18785. this.position.z = position.z;
  18786. this.scaling.x = scale.x;
  18787. this.scaling.y = scale.y;
  18788. this.scaling.z = scale.z;
  18789. }
  18790. this.parent = node;
  18791. return this;
  18792. };
  18793. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18794. get: function () {
  18795. return this._nonUniformScaling;
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18801. if (this._nonUniformScaling === value) {
  18802. return false;
  18803. }
  18804. this._nonUniformScaling = true;
  18805. return true;
  18806. };
  18807. /**
  18808. * Attach the current TransformNode to another TransformNode associated with a bone
  18809. * @param bone Bone affecting the TransformNode
  18810. * @param affectedTransformNode TransformNode associated with the bone
  18811. */
  18812. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18813. this._transformToBoneReferal = affectedTransformNode;
  18814. this.parent = bone;
  18815. if (bone.getWorldMatrix().determinant() < 0) {
  18816. this.scalingDeterminant *= -1;
  18817. }
  18818. return this;
  18819. };
  18820. TransformNode.prototype.detachFromBone = function () {
  18821. if (!this.parent) {
  18822. return this;
  18823. }
  18824. if (this.parent.getWorldMatrix().determinant() < 0) {
  18825. this.scalingDeterminant *= -1;
  18826. }
  18827. this._transformToBoneReferal = null;
  18828. this.parent = null;
  18829. return this;
  18830. };
  18831. /**
  18832. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18833. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18834. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18835. * The passed axis is also normalized.
  18836. * Returns the TransformNode.
  18837. */
  18838. TransformNode.prototype.rotate = function (axis, amount, space) {
  18839. axis.normalize();
  18840. if (!this.rotationQuaternion) {
  18841. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18842. this.rotation = BABYLON.Vector3.Zero();
  18843. }
  18844. var rotationQuaternion;
  18845. if (!space || space === BABYLON.Space.LOCAL) {
  18846. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18847. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18848. }
  18849. else {
  18850. if (this.parent) {
  18851. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18852. invertParentWorldMatrix.invert();
  18853. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18854. }
  18855. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18856. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18857. }
  18858. return this;
  18859. };
  18860. /**
  18861. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18862. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18863. * The passed axis is also normalized.
  18864. * Returns the TransformNode.
  18865. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18866. */
  18867. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18868. axis.normalize();
  18869. if (!this.rotationQuaternion) {
  18870. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18871. this.rotation.copyFromFloats(0, 0, 0);
  18872. }
  18873. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18874. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18875. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18876. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18877. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18878. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18879. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18880. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18881. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18882. return this;
  18883. };
  18884. /**
  18885. * Translates the mesh along the axis vector for the passed distance in the given space.
  18886. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18887. * Returns the TransformNode.
  18888. */
  18889. TransformNode.prototype.translate = function (axis, distance, space) {
  18890. var displacementVector = axis.scale(distance);
  18891. if (!space || space === BABYLON.Space.LOCAL) {
  18892. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18893. this.setPositionWithLocalVector(tempV3);
  18894. }
  18895. else {
  18896. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18897. }
  18898. return this;
  18899. };
  18900. /**
  18901. * Adds a rotation step to the mesh current rotation.
  18902. * x, y, z are Euler angles expressed in radians.
  18903. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18904. * This means this rotation is made in the mesh local space only.
  18905. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18906. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18907. * ```javascript
  18908. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18909. * ```
  18910. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18911. * 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.
  18912. * Returns the TransformNode.
  18913. */
  18914. TransformNode.prototype.addRotation = function (x, y, z) {
  18915. var rotationQuaternion;
  18916. if (this.rotationQuaternion) {
  18917. rotationQuaternion = this.rotationQuaternion;
  18918. }
  18919. else {
  18920. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18921. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18922. }
  18923. var accumulation = BABYLON.Tmp.Quaternion[0];
  18924. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18925. rotationQuaternion.multiplyInPlace(accumulation);
  18926. if (!this.rotationQuaternion) {
  18927. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18928. }
  18929. return this;
  18930. };
  18931. /**
  18932. * Computes the mesh World matrix and returns it.
  18933. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18934. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18935. * If the parameter `force`is set to `true`, the actual computation is done.
  18936. * Returns the mesh World Matrix.
  18937. */
  18938. TransformNode.prototype.computeWorldMatrix = function (force) {
  18939. if (this._isWorldMatrixFrozen) {
  18940. return this._worldMatrix;
  18941. }
  18942. if (!force && this.isSynchronized(true)) {
  18943. this._currentRenderId = this.getScene().getRenderId();
  18944. return this._worldMatrix;
  18945. }
  18946. this._cache.position.copyFrom(this.position);
  18947. this._cache.scaling.copyFrom(this.scaling);
  18948. this._cache.pivotMatrixUpdated = false;
  18949. this._cache.billboardMode = this.billboardMode;
  18950. this._currentRenderId = this.getScene().getRenderId();
  18951. this._childRenderId = this.getScene().getRenderId();
  18952. this._isDirty = false;
  18953. // Scaling
  18954. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18955. // Rotation
  18956. //rotate, if quaternion is set and rotation was used
  18957. if (this.rotationQuaternion) {
  18958. var len = this.rotation.length();
  18959. if (len) {
  18960. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18961. this.rotation.copyFromFloats(0, 0, 0);
  18962. }
  18963. }
  18964. if (this.rotationQuaternion) {
  18965. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18966. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18967. }
  18968. else {
  18969. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18970. this._cache.rotation.copyFrom(this.rotation);
  18971. }
  18972. // Translation
  18973. var camera = this.getScene().activeCamera;
  18974. if (this.infiniteDistance && !this.parent && camera) {
  18975. var cameraWorldMatrix = camera.getWorldMatrix();
  18976. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18977. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18978. }
  18979. else {
  18980. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18981. }
  18982. // Composing transformations
  18983. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18984. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18985. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18986. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18987. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18988. // Need to decompose each rotation here
  18989. var currentPosition = BABYLON.Tmp.Vector3[3];
  18990. if (this.parent && this.parent.getWorldMatrix) {
  18991. if (this._transformToBoneReferal) {
  18992. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18993. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18994. }
  18995. else {
  18996. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18997. }
  18998. }
  18999. else {
  19000. currentPosition.copyFrom(this.position);
  19001. }
  19002. currentPosition.subtractInPlace(camera.globalPosition);
  19003. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19004. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19005. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19006. }
  19007. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19008. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19009. }
  19010. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19011. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19012. }
  19013. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19014. }
  19015. else {
  19016. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19017. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19018. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19019. }
  19020. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19021. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19022. }
  19023. // Local world
  19024. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19025. // Parent
  19026. if (this.parent && this.parent.getWorldMatrix) {
  19027. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19028. if (this._transformToBoneReferal) {
  19029. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19030. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19031. }
  19032. else {
  19033. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19034. }
  19035. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19036. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19037. this._worldMatrix.copyFrom(this._localWorld);
  19038. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19039. }
  19040. else {
  19041. if (this._transformToBoneReferal) {
  19042. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19043. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19044. }
  19045. else {
  19046. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19047. }
  19048. }
  19049. this._markSyncedWithParent();
  19050. }
  19051. else {
  19052. this._worldMatrix.copyFrom(this._localWorld);
  19053. }
  19054. // Post multiply inverse of pivotMatrix
  19055. if (this._postMultiplyPivotMatrix) {
  19056. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19057. }
  19058. // Normal matrix
  19059. if (this.scaling.isNonUniform) {
  19060. this._updateNonUniformScalingState(true);
  19061. }
  19062. else if (this.parent && this.parent._nonUniformScaling) {
  19063. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19064. }
  19065. else {
  19066. this._updateNonUniformScalingState(false);
  19067. }
  19068. this._afterComputeWorldMatrix();
  19069. // Absolute position
  19070. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19071. // Callbacks
  19072. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19073. if (!this._poseMatrix) {
  19074. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19075. }
  19076. // Cache the determinant
  19077. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19078. return this._worldMatrix;
  19079. };
  19080. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19081. };
  19082. /**
  19083. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19084. * @param func: callback function to add
  19085. *
  19086. * Returns the TransformNode.
  19087. */
  19088. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19089. this.onAfterWorldMatrixUpdateObservable.add(func);
  19090. return this;
  19091. };
  19092. /**
  19093. * Removes a registered callback function.
  19094. * Returns the TransformNode.
  19095. */
  19096. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19097. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19098. return this;
  19099. };
  19100. /**
  19101. * Clone the current transform node
  19102. * Returns the new transform node
  19103. * @param name Name of the new clone
  19104. * @param newParent New parent for the clone
  19105. * @param doNotCloneChildren Do not clone children hierarchy
  19106. */
  19107. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19108. var _this = this;
  19109. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19110. result.name = name;
  19111. result.id = name;
  19112. if (newParent) {
  19113. result.parent = newParent;
  19114. }
  19115. if (!doNotCloneChildren) {
  19116. // Children
  19117. var directDescendants = this.getDescendants(true);
  19118. for (var index = 0; index < directDescendants.length; index++) {
  19119. var child = directDescendants[index];
  19120. if (child.clone) {
  19121. child.clone(name + "." + child.name, result);
  19122. }
  19123. }
  19124. }
  19125. return result;
  19126. };
  19127. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19128. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19129. serializationObject.type = this.getClassName();
  19130. // Parent
  19131. if (this.parent) {
  19132. serializationObject.parentId = this.parent.id;
  19133. }
  19134. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19135. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19136. }
  19137. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19138. serializationObject.isEnabled = this.isEnabled();
  19139. // Parent
  19140. if (this.parent) {
  19141. serializationObject.parentId = this.parent.id;
  19142. }
  19143. return serializationObject;
  19144. };
  19145. // Statics
  19146. /**
  19147. * Returns a new TransformNode object parsed from the source provided.
  19148. * The parameter `parsedMesh` is the source.
  19149. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19150. */
  19151. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19152. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19153. if (BABYLON.Tags) {
  19154. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19155. }
  19156. if (parsedTransformNode.localMatrix) {
  19157. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19158. }
  19159. else if (parsedTransformNode.pivotMatrix) {
  19160. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19161. }
  19162. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19163. // Parent
  19164. if (parsedTransformNode.parentId) {
  19165. transformNode._waitingParentId = parsedTransformNode.parentId;
  19166. }
  19167. return transformNode;
  19168. };
  19169. /**
  19170. * Releases resources associated with this transform node.
  19171. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19172. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19173. */
  19174. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19175. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19176. // Animations
  19177. this.getScene().stopAnimation(this);
  19178. // Remove from scene
  19179. this.getScene().removeTransformNode(this);
  19180. this.onAfterWorldMatrixUpdateObservable.clear();
  19181. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19182. };
  19183. // Statics
  19184. TransformNode.BILLBOARDMODE_NONE = 0;
  19185. TransformNode.BILLBOARDMODE_X = 1;
  19186. TransformNode.BILLBOARDMODE_Y = 2;
  19187. TransformNode.BILLBOARDMODE_Z = 4;
  19188. TransformNode.BILLBOARDMODE_ALL = 7;
  19189. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19190. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19191. __decorate([
  19192. BABYLON.serializeAsVector3()
  19193. ], TransformNode.prototype, "_rotation", void 0);
  19194. __decorate([
  19195. BABYLON.serializeAsQuaternion()
  19196. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19197. __decorate([
  19198. BABYLON.serializeAsVector3()
  19199. ], TransformNode.prototype, "_scaling", void 0);
  19200. __decorate([
  19201. BABYLON.serialize()
  19202. ], TransformNode.prototype, "billboardMode", void 0);
  19203. __decorate([
  19204. BABYLON.serialize()
  19205. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19206. __decorate([
  19207. BABYLON.serialize()
  19208. ], TransformNode.prototype, "infiniteDistance", void 0);
  19209. __decorate([
  19210. BABYLON.serializeAsVector3()
  19211. ], TransformNode.prototype, "position", void 0);
  19212. return TransformNode;
  19213. }(BABYLON.Node));
  19214. BABYLON.TransformNode = TransformNode;
  19215. })(BABYLON || (BABYLON = {}));
  19216. //# sourceMappingURL=babylon.transformNode.js.map
  19217. var BABYLON;
  19218. (function (BABYLON) {
  19219. /**
  19220. * Class used to store all common mesh properties
  19221. */
  19222. var AbstractMesh = /** @class */ (function (_super) {
  19223. __extends(AbstractMesh, _super);
  19224. // Constructor
  19225. /**
  19226. * Creates a new AbstractMesh
  19227. * @param name defines the name of the mesh
  19228. * @param scene defines the hosting scene
  19229. */
  19230. function AbstractMesh(name, scene) {
  19231. if (scene === void 0) { scene = null; }
  19232. var _this = _super.call(this, name, scene, false) || this;
  19233. _this._facetNb = 0; // facet number
  19234. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19235. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19236. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19237. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19238. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19239. _this._subDiv = {
  19240. max: 1,
  19241. X: 1,
  19242. Y: 1,
  19243. Z: 1
  19244. };
  19245. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19246. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19247. // Events
  19248. /**
  19249. * An event triggered when this mesh collides with another one
  19250. */
  19251. _this.onCollideObservable = new BABYLON.Observable();
  19252. /**
  19253. * An event triggered when the collision's position changes
  19254. */
  19255. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19256. /**
  19257. * An event triggered when material is changed
  19258. */
  19259. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19260. // Properties
  19261. /**
  19262. * Gets or sets the orientation for POV movement & rotation
  19263. */
  19264. _this.definedFacingForward = true;
  19265. /**
  19266. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19267. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19268. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19269. * @see http://doc.babylonjs.com/features/occlusionquery
  19270. */
  19271. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19272. /**
  19273. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19274. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19275. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19276. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19277. * @see http://doc.babylonjs.com/features/occlusionquery
  19278. */
  19279. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19280. /**
  19281. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19282. * The default value is -1 which means don't break the query and wait till the result
  19283. * @see http://doc.babylonjs.com/features/occlusionquery
  19284. */
  19285. _this.occlusionRetryCount = -1;
  19286. _this._occlusionInternalRetryCounter = 0;
  19287. _this._isOccluded = false;
  19288. _this._isOcclusionQueryInProgress = false;
  19289. _this._visibility = 1.0;
  19290. /** Gets or sets the alpha index used to sort transparent meshes
  19291. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19292. */
  19293. _this.alphaIndex = Number.MAX_VALUE;
  19294. /**
  19295. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19296. */
  19297. _this.isVisible = true;
  19298. /**
  19299. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19300. */
  19301. _this.isPickable = true;
  19302. /**
  19303. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19304. */
  19305. _this.showBoundingBox = false;
  19306. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19307. _this.showSubMeshesBoundingBox = false;
  19308. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19309. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19310. */
  19311. _this.isBlocker = false;
  19312. /**
  19313. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19314. */
  19315. _this.enablePointerMoveEvents = false;
  19316. /**
  19317. * Specifies the rendering group id for this mesh (0 by default)
  19318. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19319. */
  19320. _this.renderingGroupId = 0;
  19321. _this._receiveShadows = false;
  19322. /**
  19323. * Gets or sets a boolean indicating if the outline must be rendered as well
  19324. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19325. */
  19326. _this.renderOutline = false;
  19327. /** Defines color to use when rendering outline */
  19328. _this.outlineColor = BABYLON.Color3.Red();
  19329. /** Define width to use when rendering outline */
  19330. _this.outlineWidth = 0.02;
  19331. /**
  19332. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19333. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19334. */
  19335. _this.renderOverlay = false;
  19336. /** Defines color to use when rendering overlay */
  19337. _this.overlayColor = BABYLON.Color3.Red();
  19338. /** Defines alpha to use when rendering overlay */
  19339. _this.overlayAlpha = 0.5;
  19340. _this._hasVertexAlpha = false;
  19341. _this._useVertexColors = true;
  19342. _this._computeBonesUsingShaders = true;
  19343. _this._numBoneInfluencers = 4;
  19344. _this._applyFog = true;
  19345. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19346. _this.useOctreeForRenderingSelection = true;
  19347. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19348. _this.useOctreeForPicking = true;
  19349. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19350. _this.useOctreeForCollisions = true;
  19351. _this._layerMask = 0x0FFFFFFF;
  19352. /**
  19353. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19354. */
  19355. _this.alwaysSelectAsActiveMesh = false;
  19356. /**
  19357. * Gets or sets the current action manager
  19358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19359. */
  19360. _this.actionManager = null;
  19361. /**
  19362. * Gets or sets impostor used for physic simulation
  19363. * @see http://doc.babylonjs.com/features/physics_engine
  19364. */
  19365. _this.physicsImpostor = null;
  19366. // Collisions
  19367. _this._checkCollisions = false;
  19368. _this._collisionMask = -1;
  19369. _this._collisionGroup = -1;
  19370. /**
  19371. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19372. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19373. */
  19374. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19375. /**
  19376. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19377. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19378. */
  19379. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19380. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19381. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19382. // Edges
  19383. /**
  19384. * Defines edge width used when edgesRenderer is enabled
  19385. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19386. */
  19387. _this.edgesWidth = 1;
  19388. /**
  19389. * Defines edge color used when edgesRenderer is enabled
  19390. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19391. */
  19392. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19393. // Cache
  19394. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19395. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19396. /** @hidden */
  19397. _this._renderId = 0;
  19398. /** @hidden */
  19399. _this._intersectionsInProgress = new Array();
  19400. /** @hidden */
  19401. _this._unIndexed = false;
  19402. /** @hidden */
  19403. _this._lightSources = new Array();
  19404. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19405. if (collidedMesh === void 0) { collidedMesh = null; }
  19406. //TODO move this to the collision coordinator!
  19407. if (_this.getScene().workerCollisions)
  19408. newPosition.multiplyInPlace(_this._collider._radius);
  19409. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19410. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19411. _this.position.addInPlace(_this._diffPositionForCollisions);
  19412. }
  19413. if (collidedMesh) {
  19414. _this.onCollideObservable.notifyObservers(collidedMesh);
  19415. }
  19416. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19417. };
  19418. _this.getScene().addMesh(_this);
  19419. _this._resyncLightSources();
  19420. return _this;
  19421. }
  19422. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19423. /**
  19424. * No billboard
  19425. */
  19426. get: function () {
  19427. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19433. /** Billboard on X axis */
  19434. get: function () {
  19435. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19441. /** Billboard on Y axis */
  19442. get: function () {
  19443. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19449. /** Billboard on Z axis */
  19450. get: function () {
  19451. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19452. },
  19453. enumerable: true,
  19454. configurable: true
  19455. });
  19456. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19457. /** Billboard on all axes */
  19458. get: function () {
  19459. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19465. /**
  19466. * Gets the number of facets in the mesh
  19467. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19468. */
  19469. get: function () {
  19470. return this._facetNb;
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19476. /**
  19477. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19478. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19479. */
  19480. get: function () {
  19481. return this._partitioningSubdivisions;
  19482. },
  19483. set: function (nb) {
  19484. this._partitioningSubdivisions = nb;
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19490. /**
  19491. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19492. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19493. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19494. */
  19495. get: function () {
  19496. return this._partitioningBBoxRatio;
  19497. },
  19498. set: function (ratio) {
  19499. this._partitioningBBoxRatio = ratio;
  19500. },
  19501. enumerable: true,
  19502. configurable: true
  19503. });
  19504. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19505. /**
  19506. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19507. * Works only for updatable meshes.
  19508. * Doesn't work with multi-materials
  19509. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19510. */
  19511. get: function () {
  19512. return this._facetDepthSort;
  19513. },
  19514. set: function (sort) {
  19515. this._facetDepthSort = sort;
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19521. /**
  19522. * The location (Vector3) where the facet depth sort must be computed from.
  19523. * By default, the active camera position.
  19524. * Used only when facet depth sort is enabled
  19525. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19526. */
  19527. get: function () {
  19528. return this._facetDepthSortFrom;
  19529. },
  19530. set: function (location) {
  19531. this._facetDepthSortFrom = location;
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19537. /**
  19538. * gets a boolean indicating if facetData is enabled
  19539. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19540. */
  19541. get: function () {
  19542. return this._facetDataEnabled;
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. /** @hidden */
  19548. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19549. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19550. return false;
  19551. }
  19552. this._markSubMeshesAsMiscDirty();
  19553. return true;
  19554. };
  19555. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19556. /** Set a function to call when this mesh collides with another one */
  19557. set: function (callback) {
  19558. if (this._onCollideObserver) {
  19559. this.onCollideObservable.remove(this._onCollideObserver);
  19560. }
  19561. this._onCollideObserver = this.onCollideObservable.add(callback);
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19567. /** Set a function to call when the collision's position changes */
  19568. set: function (callback) {
  19569. if (this._onCollisionPositionChangeObserver) {
  19570. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19571. }
  19572. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19578. /**
  19579. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19580. * @see http://doc.babylonjs.com/features/occlusionquery
  19581. */
  19582. get: function () {
  19583. return this._isOccluded;
  19584. },
  19585. set: function (value) {
  19586. this._isOccluded = value;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19592. /**
  19593. * Flag to check the progress status of the query
  19594. * @see http://doc.babylonjs.com/features/occlusionquery
  19595. */
  19596. get: function () {
  19597. return this._isOcclusionQueryInProgress;
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19603. /**
  19604. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19605. */
  19606. get: function () {
  19607. return this._visibility;
  19608. },
  19609. /**
  19610. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19611. */
  19612. set: function (value) {
  19613. if (this._visibility === value) {
  19614. return;
  19615. }
  19616. this._visibility = value;
  19617. this._markSubMeshesAsMiscDirty();
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Object.defineProperty(AbstractMesh.prototype, "material", {
  19623. /** Gets or sets current material */
  19624. get: function () {
  19625. return this._material;
  19626. },
  19627. set: function (value) {
  19628. if (this._material === value) {
  19629. return;
  19630. }
  19631. this._material = value;
  19632. if (this.onMaterialChangedObservable.hasObservers) {
  19633. this.onMaterialChangedObservable.notifyObservers(this);
  19634. }
  19635. if (!this.subMeshes) {
  19636. return;
  19637. }
  19638. this._unBindEffect();
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19644. /**
  19645. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19646. * @see http://doc.babylonjs.com/babylon101/shadows
  19647. */
  19648. get: function () {
  19649. return this._receiveShadows;
  19650. },
  19651. set: function (value) {
  19652. if (this._receiveShadows === value) {
  19653. return;
  19654. }
  19655. this._receiveShadows = value;
  19656. this._markSubMeshesAsLightDirty();
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19662. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19663. get: function () {
  19664. return this._hasVertexAlpha;
  19665. },
  19666. set: function (value) {
  19667. if (this._hasVertexAlpha === value) {
  19668. return;
  19669. }
  19670. this._hasVertexAlpha = value;
  19671. this._markSubMeshesAsAttributesDirty();
  19672. this._markSubMeshesAsMiscDirty();
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19678. /** 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) */
  19679. get: function () {
  19680. return this._useVertexColors;
  19681. },
  19682. set: function (value) {
  19683. if (this._useVertexColors === value) {
  19684. return;
  19685. }
  19686. this._useVertexColors = value;
  19687. this._markSubMeshesAsAttributesDirty();
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19693. /**
  19694. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19695. */
  19696. get: function () {
  19697. return this._computeBonesUsingShaders;
  19698. },
  19699. set: function (value) {
  19700. if (this._computeBonesUsingShaders === value) {
  19701. return;
  19702. }
  19703. this._computeBonesUsingShaders = value;
  19704. this._markSubMeshesAsAttributesDirty();
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19710. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19711. get: function () {
  19712. return this._numBoneInfluencers;
  19713. },
  19714. set: function (value) {
  19715. if (this._numBoneInfluencers === value) {
  19716. return;
  19717. }
  19718. this._numBoneInfluencers = value;
  19719. this._markSubMeshesAsAttributesDirty();
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19725. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19726. get: function () {
  19727. return this._applyFog;
  19728. },
  19729. set: function (value) {
  19730. if (this._applyFog === value) {
  19731. return;
  19732. }
  19733. this._applyFog = value;
  19734. this._markSubMeshesAsMiscDirty();
  19735. },
  19736. enumerable: true,
  19737. configurable: true
  19738. });
  19739. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19740. /**
  19741. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19742. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19743. */
  19744. get: function () {
  19745. return this._layerMask;
  19746. },
  19747. set: function (value) {
  19748. if (value === this._layerMask) {
  19749. return;
  19750. }
  19751. this._layerMask = value;
  19752. this._resyncLightSources();
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19758. /**
  19759. * Gets or sets a collision mask used to mask collisions (default is -1).
  19760. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19761. */
  19762. get: function () {
  19763. return this._collisionMask;
  19764. },
  19765. set: function (mask) {
  19766. this._collisionMask = !isNaN(mask) ? mask : -1;
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19772. /**
  19773. * Gets or sets the current collision group mask (-1 by default).
  19774. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19775. */
  19776. get: function () {
  19777. return this._collisionGroup;
  19778. },
  19779. set: function (mask) {
  19780. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19781. },
  19782. enumerable: true,
  19783. configurable: true
  19784. });
  19785. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19786. /** @hidden */
  19787. get: function () {
  19788. return null;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19794. get: function () {
  19795. return this._skeleton;
  19796. },
  19797. /**
  19798. * Gets or sets a skeleton to apply skining transformations
  19799. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19800. */
  19801. set: function (value) {
  19802. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19803. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19804. }
  19805. if (value && value.needInitialSkinMatrix) {
  19806. value._registerMeshWithPoseMatrix(this);
  19807. }
  19808. this._skeleton = value;
  19809. if (!this._skeleton) {
  19810. this._bonesTransformMatrices = null;
  19811. }
  19812. this._markSubMeshesAsAttributesDirty();
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. /**
  19818. * Returns the string "AbstractMesh"
  19819. * @returns "AbstractMesh"
  19820. */
  19821. AbstractMesh.prototype.getClassName = function () {
  19822. return "AbstractMesh";
  19823. };
  19824. /**
  19825. * Gets a string representation of the current mesh
  19826. * @param fullDetails defines a boolean indicating if full details must be included
  19827. * @returns a string representation of the current mesh
  19828. */
  19829. AbstractMesh.prototype.toString = function (fullDetails) {
  19830. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19831. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19832. if (this._skeleton) {
  19833. ret += ", skeleton: " + this._skeleton.name;
  19834. }
  19835. if (fullDetails) {
  19836. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19837. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19838. }
  19839. return ret;
  19840. };
  19841. /** @hidden */
  19842. AbstractMesh.prototype._rebuild = function () {
  19843. if (this._occlusionQuery) {
  19844. this._occlusionQuery = null;
  19845. }
  19846. if (this._edgesRenderer) {
  19847. this._edgesRenderer._rebuild();
  19848. }
  19849. if (!this.subMeshes) {
  19850. return;
  19851. }
  19852. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19853. var subMesh = _a[_i];
  19854. subMesh._rebuild();
  19855. }
  19856. };
  19857. /** @hidden */
  19858. AbstractMesh.prototype._resyncLightSources = function () {
  19859. this._lightSources.length = 0;
  19860. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19861. var light = _a[_i];
  19862. if (!light.isEnabled()) {
  19863. continue;
  19864. }
  19865. if (light.canAffectMesh(this)) {
  19866. this._lightSources.push(light);
  19867. }
  19868. }
  19869. this._markSubMeshesAsLightDirty();
  19870. };
  19871. /** @hidden */
  19872. AbstractMesh.prototype._resyncLighSource = function (light) {
  19873. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19874. var index = this._lightSources.indexOf(light);
  19875. if (index === -1) {
  19876. if (!isIn) {
  19877. return;
  19878. }
  19879. this._lightSources.push(light);
  19880. }
  19881. else {
  19882. if (isIn) {
  19883. return;
  19884. }
  19885. this._lightSources.splice(index, 1);
  19886. }
  19887. this._markSubMeshesAsLightDirty();
  19888. };
  19889. /** @hidden */
  19890. AbstractMesh.prototype._unBindEffect = function () {
  19891. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19892. var subMesh = _a[_i];
  19893. subMesh.setEffect(null);
  19894. }
  19895. };
  19896. /** @hidden */
  19897. AbstractMesh.prototype._removeLightSource = function (light) {
  19898. var index = this._lightSources.indexOf(light);
  19899. if (index === -1) {
  19900. return;
  19901. }
  19902. this._lightSources.splice(index, 1);
  19903. this._markSubMeshesAsLightDirty();
  19904. };
  19905. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19906. if (!this.subMeshes) {
  19907. return;
  19908. }
  19909. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19910. var subMesh = _a[_i];
  19911. if (subMesh._materialDefines) {
  19912. func(subMesh._materialDefines);
  19913. }
  19914. }
  19915. };
  19916. /** @hidden */
  19917. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19918. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19919. };
  19920. /** @hidden */
  19921. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19922. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19923. };
  19924. /** @hidden */
  19925. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19926. if (!this.subMeshes) {
  19927. return;
  19928. }
  19929. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19930. var subMesh = _a[_i];
  19931. var material = subMesh.getMaterial();
  19932. if (material) {
  19933. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19934. }
  19935. }
  19936. };
  19937. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19938. /**
  19939. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19940. */
  19941. get: function () {
  19942. return this._scaling;
  19943. },
  19944. set: function (newScaling) {
  19945. this._scaling = newScaling;
  19946. if (this.physicsImpostor) {
  19947. this.physicsImpostor.forceUpdate();
  19948. }
  19949. },
  19950. enumerable: true,
  19951. configurable: true
  19952. });
  19953. // Methods
  19954. /**
  19955. * Disables the mesh edge rendering mode
  19956. * @returns the currentAbstractMesh
  19957. */
  19958. AbstractMesh.prototype.disableEdgesRendering = function () {
  19959. if (this._edgesRenderer) {
  19960. this._edgesRenderer.dispose();
  19961. this._edgesRenderer = null;
  19962. }
  19963. return this;
  19964. };
  19965. /**
  19966. * Enables the edge rendering mode on the mesh.
  19967. * This mode makes the mesh edges visible
  19968. * @param epsilon defines the maximal distance between two angles to detect a face
  19969. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19970. * @returns the currentAbstractMesh
  19971. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19972. */
  19973. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19974. if (epsilon === void 0) { epsilon = 0.95; }
  19975. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19976. this.disableEdgesRendering();
  19977. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19978. return this;
  19979. };
  19980. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19981. /**
  19982. * Returns true if the mesh is blocked. Implemented by child classes
  19983. */
  19984. get: function () {
  19985. return false;
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. /**
  19991. * Returns the mesh itself by default. Implemented by child classes
  19992. * @param camera defines the camera to use to pick the right LOD level
  19993. * @returns the currentAbstractMesh
  19994. */
  19995. AbstractMesh.prototype.getLOD = function (camera) {
  19996. return this;
  19997. };
  19998. /**
  19999. * Returns 0 by default. Implemented by child classes
  20000. * @returns an integer
  20001. */
  20002. AbstractMesh.prototype.getTotalVertices = function () {
  20003. return 0;
  20004. };
  20005. /**
  20006. * Returns null by default. Implemented by child classes
  20007. * @returns null
  20008. */
  20009. AbstractMesh.prototype.getIndices = function () {
  20010. return null;
  20011. };
  20012. /**
  20013. * Returns the array of the requested vertex data kind. Implemented by child classes
  20014. * @param kind defines the vertex data kind to use
  20015. * @returns null
  20016. */
  20017. AbstractMesh.prototype.getVerticesData = function (kind) {
  20018. return null;
  20019. };
  20020. /**
  20021. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20022. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20023. * Note that a new underlying VertexBuffer object is created each call.
  20024. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20025. * @param kind defines vertex data kind:
  20026. * * BABYLON.VertexBuffer.PositionKind
  20027. * * BABYLON.VertexBuffer.UVKind
  20028. * * BABYLON.VertexBuffer.UV2Kind
  20029. * * BABYLON.VertexBuffer.UV3Kind
  20030. * * BABYLON.VertexBuffer.UV4Kind
  20031. * * BABYLON.VertexBuffer.UV5Kind
  20032. * * BABYLON.VertexBuffer.UV6Kind
  20033. * * BABYLON.VertexBuffer.ColorKind
  20034. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20035. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20036. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20037. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20038. * @param data defines the data source
  20039. * @param updatable defines if the data must be flagged as updatable (or static)
  20040. * @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
  20041. * @returns the current mesh
  20042. */
  20043. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20044. return this;
  20045. };
  20046. /**
  20047. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20048. * If the mesh has no geometry, it is simply returned as it is.
  20049. * @param kind defines vertex data kind:
  20050. * * BABYLON.VertexBuffer.PositionKind
  20051. * * BABYLON.VertexBuffer.UVKind
  20052. * * BABYLON.VertexBuffer.UV2Kind
  20053. * * BABYLON.VertexBuffer.UV3Kind
  20054. * * BABYLON.VertexBuffer.UV4Kind
  20055. * * BABYLON.VertexBuffer.UV5Kind
  20056. * * BABYLON.VertexBuffer.UV6Kind
  20057. * * BABYLON.VertexBuffer.ColorKind
  20058. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20059. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20060. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20061. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20062. * @param data defines the data source
  20063. * @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
  20064. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20065. * @returns the current mesh
  20066. */
  20067. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20068. return this;
  20069. };
  20070. /**
  20071. * Sets the mesh indices,
  20072. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20073. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20074. * @param totalVertices Defines the total number of vertices
  20075. * @returns the current mesh
  20076. */
  20077. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20078. return this;
  20079. };
  20080. /**
  20081. * Gets a boolean indicating if specific vertex data is present
  20082. * @param kind defines the vertex data kind to use
  20083. * @returns true is data kind is present
  20084. */
  20085. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20086. return false;
  20087. };
  20088. /**
  20089. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20090. * @returns a BoundingInfo
  20091. */
  20092. AbstractMesh.prototype.getBoundingInfo = function () {
  20093. if (this._masterMesh) {
  20094. return this._masterMesh.getBoundingInfo();
  20095. }
  20096. if (!this._boundingInfo) {
  20097. // this._boundingInfo is being created here
  20098. this._updateBoundingInfo();
  20099. }
  20100. // cannot be null.
  20101. return this._boundingInfo;
  20102. };
  20103. /**
  20104. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20105. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20106. * @returns the current mesh
  20107. */
  20108. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20109. if (includeDescendants === void 0) { includeDescendants = true; }
  20110. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20111. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20112. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20113. if (maxDimension === 0) {
  20114. return this;
  20115. }
  20116. var scale = 1 / maxDimension;
  20117. this.scaling.scaleInPlace(scale);
  20118. return this;
  20119. };
  20120. /**
  20121. * Overwrite the current bounding info
  20122. * @param boundingInfo defines the new bounding info
  20123. * @returns the current mesh
  20124. */
  20125. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20126. this._boundingInfo = boundingInfo;
  20127. return this;
  20128. };
  20129. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20130. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20131. get: function () {
  20132. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. /** @hidden */
  20138. AbstractMesh.prototype._preActivate = function () {
  20139. };
  20140. /** @hidden */
  20141. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20142. };
  20143. /** @hidden */
  20144. AbstractMesh.prototype._activate = function (renderId) {
  20145. this._renderId = renderId;
  20146. };
  20147. /**
  20148. * Gets the current world matrix
  20149. * @returns a Matrix
  20150. */
  20151. AbstractMesh.prototype.getWorldMatrix = function () {
  20152. if (this._masterMesh) {
  20153. return this._masterMesh.getWorldMatrix();
  20154. }
  20155. return _super.prototype.getWorldMatrix.call(this);
  20156. };
  20157. /** @hidden */
  20158. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20159. if (this._masterMesh) {
  20160. return this._masterMesh._getWorldMatrixDeterminant();
  20161. }
  20162. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20163. };
  20164. // ================================== Point of View Movement =================================
  20165. /**
  20166. * Perform relative position change from the point of view of behind the front of the mesh.
  20167. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20168. * Supports definition of mesh facing forward or backward
  20169. * @param amountRight defines the distance on the right axis
  20170. * @param amountUp defines the distance on the up axis
  20171. * @param amountForward defines the distance on the forward axis
  20172. * @returns the current mesh
  20173. */
  20174. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20175. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20176. return this;
  20177. };
  20178. /**
  20179. * Calculate relative position change from the point of view of behind the front of the mesh.
  20180. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20181. * Supports definition of mesh facing forward or backward
  20182. * @param amountRight defines the distance on the right axis
  20183. * @param amountUp defines the distance on the up axis
  20184. * @param amountForward defines the distance on the forward axis
  20185. * @returns the new displacement vector
  20186. */
  20187. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20188. var rotMatrix = new BABYLON.Matrix();
  20189. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20190. rotQuaternion.toRotationMatrix(rotMatrix);
  20191. var translationDelta = BABYLON.Vector3.Zero();
  20192. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20193. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20194. return translationDelta;
  20195. };
  20196. // ================================== Point of View Rotation =================================
  20197. /**
  20198. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20199. * Supports definition of mesh facing forward or backward
  20200. * @param flipBack defines the flip
  20201. * @param twirlClockwise defines the twirl
  20202. * @param tiltRight defines the tilt
  20203. * @returns the current mesh
  20204. */
  20205. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20206. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20207. return this;
  20208. };
  20209. /**
  20210. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20211. * Supports definition of mesh facing forward or backward.
  20212. * @param flipBack defines the flip
  20213. * @param twirlClockwise defines the twirl
  20214. * @param tiltRight defines the tilt
  20215. * @returns the new rotation vector
  20216. */
  20217. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20218. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20219. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20220. };
  20221. /**
  20222. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20223. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20224. * @returns the new bounding vectors
  20225. */
  20226. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20227. if (includeDescendants === void 0) { includeDescendants = true; }
  20228. this.computeWorldMatrix(true);
  20229. var min;
  20230. var max;
  20231. var boundingInfo = this.getBoundingInfo();
  20232. if (!this.subMeshes) {
  20233. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20234. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20235. }
  20236. else {
  20237. min = boundingInfo.boundingBox.minimumWorld;
  20238. max = boundingInfo.boundingBox.maximumWorld;
  20239. }
  20240. if (includeDescendants) {
  20241. var descendants = this.getDescendants(false);
  20242. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20243. var descendant = descendants_1[_i];
  20244. var childMesh = descendant;
  20245. childMesh.computeWorldMatrix(true);
  20246. //make sure we have the needed params to get mix and max
  20247. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20248. continue;
  20249. }
  20250. var childBoundingInfo = childMesh.getBoundingInfo();
  20251. var boundingBox = childBoundingInfo.boundingBox;
  20252. var minBox = boundingBox.minimumWorld;
  20253. var maxBox = boundingBox.maximumWorld;
  20254. BABYLON.Tools.CheckExtends(minBox, min, max);
  20255. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20256. }
  20257. }
  20258. return {
  20259. min: min,
  20260. max: max
  20261. };
  20262. };
  20263. /** @hidden */
  20264. AbstractMesh.prototype._updateBoundingInfo = function () {
  20265. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20266. this._boundingInfo.update(this.worldMatrixFromCache);
  20267. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20268. return this;
  20269. };
  20270. /** @hidden */
  20271. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20272. if (!this.subMeshes) {
  20273. return this;
  20274. }
  20275. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20276. var subMesh = this.subMeshes[subIndex];
  20277. if (!subMesh.IsGlobal) {
  20278. subMesh.updateBoundingInfo(matrix);
  20279. }
  20280. }
  20281. return this;
  20282. };
  20283. /** @hidden */
  20284. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20285. // Bounding info
  20286. this._updateBoundingInfo();
  20287. };
  20288. /**
  20289. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20290. * A mesh is in the frustum if its bounding box intersects the frustum
  20291. * @param frustumPlanes defines the frustum to test
  20292. * @returns true if the mesh is in the frustum planes
  20293. */
  20294. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20295. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20296. };
  20297. /**
  20298. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20299. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20300. * @param frustumPlanes defines the frustum to test
  20301. * @returns true if the mesh is completely in the frustum planes
  20302. */
  20303. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20304. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20305. ;
  20306. };
  20307. /**
  20308. * True if the mesh intersects another mesh or a SolidParticle object
  20309. * @param mesh defines a target mesh or SolidParticle to test
  20310. * @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)
  20311. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20312. * @returns true if there is an intersection
  20313. */
  20314. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20315. if (precise === void 0) { precise = false; }
  20316. if (!this._boundingInfo || !mesh._boundingInfo) {
  20317. return false;
  20318. }
  20319. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20320. return true;
  20321. }
  20322. if (includeDescendants) {
  20323. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20324. var child = _a[_i];
  20325. if (child.intersectsMesh(mesh, precise, true)) {
  20326. return true;
  20327. }
  20328. }
  20329. }
  20330. return false;
  20331. };
  20332. /**
  20333. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20334. * @param point defines the point to test
  20335. * @returns true if there is an intersection
  20336. */
  20337. AbstractMesh.prototype.intersectsPoint = function (point) {
  20338. if (!this._boundingInfo) {
  20339. return false;
  20340. }
  20341. return this._boundingInfo.intersectsPoint(point);
  20342. };
  20343. /**
  20344. * Gets the current physics impostor
  20345. * @see http://doc.babylonjs.com/features/physics_engine
  20346. * @returns a physics impostor or null
  20347. */
  20348. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20349. return this.physicsImpostor;
  20350. };
  20351. /**
  20352. * Gets the position of the current mesh in camera space
  20353. * @param camera defines the camera to use
  20354. * @returns a position
  20355. */
  20356. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20357. if (camera === void 0) { camera = null; }
  20358. if (!camera) {
  20359. camera = this.getScene().activeCamera;
  20360. }
  20361. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20362. };
  20363. /**
  20364. * Returns the distance from the mesh to the active camera
  20365. * @param camera defines the camera to use
  20366. * @returns the distance
  20367. */
  20368. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20369. if (camera === void 0) { camera = null; }
  20370. if (!camera) {
  20371. camera = this.getScene().activeCamera;
  20372. }
  20373. return this.absolutePosition.subtract(camera.position).length();
  20374. };
  20375. /**
  20376. * Apply a physic impulse to the mesh
  20377. * @param force defines the force to apply
  20378. * @param contactPoint defines where to apply the force
  20379. * @returns the current mesh
  20380. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20381. */
  20382. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20383. if (!this.physicsImpostor) {
  20384. return this;
  20385. }
  20386. this.physicsImpostor.applyImpulse(force, contactPoint);
  20387. return this;
  20388. };
  20389. /**
  20390. * Creates a physic joint between two meshes
  20391. * @param otherMesh defines the other mesh to use
  20392. * @param pivot1 defines the pivot to use on this mesh
  20393. * @param pivot2 defines the pivot to use on the other mesh
  20394. * @param options defines additional options (can be plugin dependent)
  20395. * @returns the current mesh
  20396. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20397. */
  20398. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20399. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20400. return this;
  20401. }
  20402. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20403. mainPivot: pivot1,
  20404. connectedPivot: pivot2,
  20405. nativeParams: options
  20406. });
  20407. return this;
  20408. };
  20409. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20410. // Collisions
  20411. /**
  20412. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20413. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20414. */
  20415. get: function () {
  20416. return this._checkCollisions;
  20417. },
  20418. set: function (collisionEnabled) {
  20419. this._checkCollisions = collisionEnabled;
  20420. if (this.getScene().workerCollisions) {
  20421. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20422. }
  20423. },
  20424. enumerable: true,
  20425. configurable: true
  20426. });
  20427. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20428. /**
  20429. * Gets Collider object used to compute collisions (not physics)
  20430. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20431. */
  20432. get: function () {
  20433. return this._collider;
  20434. },
  20435. enumerable: true,
  20436. configurable: true
  20437. });
  20438. /**
  20439. * Move the mesh using collision engine
  20440. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20441. * @param displacement defines the requested displacement vector
  20442. * @returns the current mesh
  20443. */
  20444. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20445. var globalPosition = this.getAbsolutePosition();
  20446. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20447. if (!this._collider) {
  20448. this._collider = new BABYLON.Collider();
  20449. }
  20450. this._collider._radius = this.ellipsoid;
  20451. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20452. return this;
  20453. };
  20454. // Submeshes octree
  20455. /**
  20456. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20457. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20458. * @param maxCapacity defines the maximum size of each block (64 by default)
  20459. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20460. * @returns the new octree
  20461. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20462. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20463. */
  20464. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20465. if (maxCapacity === void 0) { maxCapacity = 64; }
  20466. if (maxDepth === void 0) { maxDepth = 2; }
  20467. if (!this._submeshesOctree) {
  20468. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20469. }
  20470. this.computeWorldMatrix(true);
  20471. var boundingInfo = this.getBoundingInfo();
  20472. // Update octree
  20473. var bbox = boundingInfo.boundingBox;
  20474. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20475. return this._submeshesOctree;
  20476. };
  20477. // Collisions
  20478. /** @hidden */
  20479. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20480. this._generatePointsArray();
  20481. if (!this._positions) {
  20482. return this;
  20483. }
  20484. // Transformation
  20485. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20486. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20487. subMesh._lastColliderWorldVertices = [];
  20488. subMesh._trianglePlanes = [];
  20489. var start = subMesh.verticesStart;
  20490. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20491. for (var i = start; i < end; i++) {
  20492. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20493. }
  20494. }
  20495. // Collide
  20496. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20497. if (collider.collisionFound) {
  20498. collider.collidedMesh = this;
  20499. }
  20500. return this;
  20501. };
  20502. /** @hidden */
  20503. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20504. var subMeshes;
  20505. var len;
  20506. // Octrees
  20507. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20508. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20509. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20510. len = intersections.length;
  20511. subMeshes = intersections.data;
  20512. }
  20513. else {
  20514. subMeshes = this.subMeshes;
  20515. len = subMeshes.length;
  20516. }
  20517. for (var index = 0; index < len; index++) {
  20518. var subMesh = subMeshes[index];
  20519. // Bounding test
  20520. if (len > 1 && !subMesh._checkCollision(collider))
  20521. continue;
  20522. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20523. }
  20524. return this;
  20525. };
  20526. /** @hidden */
  20527. AbstractMesh.prototype._checkCollision = function (collider) {
  20528. // Bounding box test
  20529. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20530. return this;
  20531. // Transformation matrix
  20532. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20533. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20534. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20535. return this;
  20536. };
  20537. // Picking
  20538. /** @hidden */
  20539. AbstractMesh.prototype._generatePointsArray = function () {
  20540. return false;
  20541. };
  20542. /**
  20543. * Checks if the passed Ray intersects with the mesh
  20544. * @param ray defines the ray to use
  20545. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20546. * @returns the picking info
  20547. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20548. */
  20549. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20550. var pickingInfo = new BABYLON.PickingInfo();
  20551. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20552. return pickingInfo;
  20553. }
  20554. if (!this._generatePointsArray()) {
  20555. return pickingInfo;
  20556. }
  20557. var intersectInfo = null;
  20558. // Octrees
  20559. var subMeshes;
  20560. var len;
  20561. if (this._submeshesOctree && this.useOctreeForPicking) {
  20562. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20563. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20564. len = intersections.length;
  20565. subMeshes = intersections.data;
  20566. }
  20567. else {
  20568. subMeshes = this.subMeshes;
  20569. len = subMeshes.length;
  20570. }
  20571. for (var index = 0; index < len; index++) {
  20572. var subMesh = subMeshes[index];
  20573. // Bounding test
  20574. if (len > 1 && !subMesh.canIntersects(ray))
  20575. continue;
  20576. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20577. if (currentIntersectInfo) {
  20578. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20579. intersectInfo = currentIntersectInfo;
  20580. intersectInfo.subMeshId = index;
  20581. if (fastCheck) {
  20582. break;
  20583. }
  20584. }
  20585. }
  20586. }
  20587. if (intersectInfo) {
  20588. // Get picked point
  20589. var world = this.getWorldMatrix();
  20590. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20591. var direction = ray.direction.clone();
  20592. direction = direction.scale(intersectInfo.distance);
  20593. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20594. var pickedPoint = worldOrigin.add(worldDirection);
  20595. // Return result
  20596. pickingInfo.hit = true;
  20597. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20598. pickingInfo.pickedPoint = pickedPoint;
  20599. pickingInfo.pickedMesh = this;
  20600. pickingInfo.bu = intersectInfo.bu || 0;
  20601. pickingInfo.bv = intersectInfo.bv || 0;
  20602. pickingInfo.faceId = intersectInfo.faceId;
  20603. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20604. return pickingInfo;
  20605. }
  20606. return pickingInfo;
  20607. };
  20608. /**
  20609. * Clones the current mesh
  20610. * @param name defines the mesh name
  20611. * @param newParent defines the new mesh parent
  20612. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20613. * @returns the new mesh
  20614. */
  20615. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20616. return null;
  20617. };
  20618. /**
  20619. * Disposes all the submeshes of the current meshnp
  20620. * @returns the current mesh
  20621. */
  20622. AbstractMesh.prototype.releaseSubMeshes = function () {
  20623. if (this.subMeshes) {
  20624. while (this.subMeshes.length) {
  20625. this.subMeshes[0].dispose();
  20626. }
  20627. }
  20628. else {
  20629. this.subMeshes = new Array();
  20630. }
  20631. return this;
  20632. };
  20633. /**
  20634. * Releases resources associated with this abstract mesh.
  20635. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20636. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20637. */
  20638. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20639. var _this = this;
  20640. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20641. var index;
  20642. // Smart Array Retainers.
  20643. this.getScene().freeActiveMeshes();
  20644. this.getScene().freeRenderingGroups();
  20645. // Action manager
  20646. if (this.actionManager !== undefined && this.actionManager !== null) {
  20647. this.actionManager.dispose();
  20648. this.actionManager = null;
  20649. }
  20650. // Skeleton
  20651. this._skeleton = null;
  20652. // Physics
  20653. if (this.physicsImpostor) {
  20654. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20655. }
  20656. // Intersections in progress
  20657. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20658. var other = this._intersectionsInProgress[index];
  20659. var pos = other._intersectionsInProgress.indexOf(this);
  20660. other._intersectionsInProgress.splice(pos, 1);
  20661. }
  20662. this._intersectionsInProgress = [];
  20663. // Lights
  20664. var lights = this.getScene().lights;
  20665. lights.forEach(function (light) {
  20666. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20667. if (meshIndex !== -1) {
  20668. light.includedOnlyMeshes.splice(meshIndex, 1);
  20669. }
  20670. meshIndex = light.excludedMeshes.indexOf(_this);
  20671. if (meshIndex !== -1) {
  20672. light.excludedMeshes.splice(meshIndex, 1);
  20673. }
  20674. // Shadow generators
  20675. var generator = light.getShadowGenerator();
  20676. if (generator) {
  20677. var shadowMap = generator.getShadowMap();
  20678. if (shadowMap && shadowMap.renderList) {
  20679. meshIndex = shadowMap.renderList.indexOf(_this);
  20680. if (meshIndex !== -1) {
  20681. shadowMap.renderList.splice(meshIndex, 1);
  20682. }
  20683. }
  20684. }
  20685. });
  20686. // Edges
  20687. if (this._edgesRenderer) {
  20688. this._edgesRenderer.dispose();
  20689. this._edgesRenderer = null;
  20690. }
  20691. // SubMeshes
  20692. if (this.getClassName() !== "InstancedMesh") {
  20693. this.releaseSubMeshes();
  20694. }
  20695. // Octree
  20696. var sceneOctree = this.getScene().selectionOctree;
  20697. if (sceneOctree !== undefined && sceneOctree !== null) {
  20698. var index = sceneOctree.dynamicContent.indexOf(this);
  20699. if (index !== -1) {
  20700. sceneOctree.dynamicContent.splice(index, 1);
  20701. }
  20702. }
  20703. // Query
  20704. var engine = this.getScene().getEngine();
  20705. if (this._occlusionQuery) {
  20706. this._isOcclusionQueryInProgress = false;
  20707. engine.deleteQuery(this._occlusionQuery);
  20708. this._occlusionQuery = null;
  20709. }
  20710. // Engine
  20711. engine.wipeCaches();
  20712. // Remove from scene
  20713. this.getScene().removeMesh(this);
  20714. if (disposeMaterialAndTextures) {
  20715. if (this.material) {
  20716. this.material.dispose(false, true);
  20717. }
  20718. }
  20719. if (!doNotRecurse) {
  20720. // Particles
  20721. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20722. if (this.getScene().particleSystems[index].emitter === this) {
  20723. this.getScene().particleSystems[index].dispose();
  20724. index--;
  20725. }
  20726. }
  20727. }
  20728. // facet data
  20729. if (this._facetDataEnabled) {
  20730. this.disableFacetData();
  20731. }
  20732. this.onAfterWorldMatrixUpdateObservable.clear();
  20733. this.onCollideObservable.clear();
  20734. this.onCollisionPositionChangeObservable.clear();
  20735. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20736. };
  20737. /**
  20738. * Adds the passed mesh as a child to the current mesh
  20739. * @param mesh defines the child mesh
  20740. * @returns the current mesh
  20741. */
  20742. AbstractMesh.prototype.addChild = function (mesh) {
  20743. mesh.setParent(this);
  20744. return this;
  20745. };
  20746. /**
  20747. * Removes the passed mesh from the current mesh children list
  20748. * @param mesh defines the child mesh
  20749. * @returns the current mesh
  20750. */
  20751. AbstractMesh.prototype.removeChild = function (mesh) {
  20752. mesh.setParent(null);
  20753. return this;
  20754. };
  20755. // Facet data
  20756. /** @hidden */
  20757. AbstractMesh.prototype._initFacetData = function () {
  20758. if (!this._facetNormals) {
  20759. this._facetNormals = new Array();
  20760. }
  20761. if (!this._facetPositions) {
  20762. this._facetPositions = new Array();
  20763. }
  20764. if (!this._facetPartitioning) {
  20765. this._facetPartitioning = new Array();
  20766. }
  20767. this._facetNb = (this.getIndices().length / 3) | 0;
  20768. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20769. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20770. for (var f = 0; f < this._facetNb; f++) {
  20771. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20772. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20773. }
  20774. this._facetDataEnabled = true;
  20775. return this;
  20776. };
  20777. /**
  20778. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20779. * This method can be called within the render loop.
  20780. * 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
  20781. * @returns the current mesh
  20782. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20783. */
  20784. AbstractMesh.prototype.updateFacetData = function () {
  20785. if (!this._facetDataEnabled) {
  20786. this._initFacetData();
  20787. }
  20788. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20789. var indices = this.getIndices();
  20790. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20791. var bInfo = this.getBoundingInfo();
  20792. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20793. // init arrays, matrix and sort function on first call
  20794. this._facetDepthSortEnabled = true;
  20795. if (indices instanceof Uint16Array) {
  20796. this._depthSortedIndices = new Uint16Array(indices);
  20797. }
  20798. else if (indices instanceof Uint32Array) {
  20799. this._depthSortedIndices = new Uint32Array(indices);
  20800. }
  20801. else {
  20802. var needs32bits = false;
  20803. for (var i = 0; i < indices.length; i++) {
  20804. if (indices[i] > 65535) {
  20805. needs32bits = true;
  20806. break;
  20807. }
  20808. }
  20809. if (needs32bits) {
  20810. this._depthSortedIndices = new Uint32Array(indices);
  20811. }
  20812. else {
  20813. this._depthSortedIndices = new Uint16Array(indices);
  20814. }
  20815. }
  20816. this._facetDepthSortFunction = function (f1, f2) {
  20817. return (f2.sqDistance - f1.sqDistance);
  20818. };
  20819. if (!this._facetDepthSortFrom) {
  20820. var camera = this.getScene().activeCamera;
  20821. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20822. }
  20823. this._depthSortedFacets = [];
  20824. for (var f = 0; f < this._facetNb; f++) {
  20825. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20826. this._depthSortedFacets.push(depthSortedFacet);
  20827. }
  20828. this._invertedMatrix = BABYLON.Matrix.Identity();
  20829. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20830. }
  20831. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20832. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20833. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20834. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20835. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20836. this._subDiv.max = this._partitioningSubdivisions;
  20837. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20838. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20839. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20840. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20841. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20842. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20843. // set the parameters for ComputeNormals()
  20844. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20845. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20846. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20847. this._facetParameters.bInfo = bInfo;
  20848. this._facetParameters.bbSize = this._bbSize;
  20849. this._facetParameters.subDiv = this._subDiv;
  20850. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20851. this._facetParameters.depthSort = this._facetDepthSort;
  20852. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20853. this.computeWorldMatrix(true);
  20854. this._worldMatrix.invertToRef(this._invertedMatrix);
  20855. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20856. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20857. }
  20858. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20859. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20860. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20861. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20862. var l = (this._depthSortedIndices.length / 3) | 0;
  20863. for (var f = 0; f < l; f++) {
  20864. var sind = this._depthSortedFacets[f].ind;
  20865. this._depthSortedIndices[f * 3] = indices[sind];
  20866. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20867. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20868. }
  20869. this.updateIndices(this._depthSortedIndices);
  20870. }
  20871. return this;
  20872. };
  20873. /**
  20874. * Returns the facetLocalNormals array.
  20875. * The normals are expressed in the mesh local spac
  20876. * @returns an array of Vector3
  20877. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20878. */
  20879. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20880. if (!this._facetNormals) {
  20881. this.updateFacetData();
  20882. }
  20883. return this._facetNormals;
  20884. };
  20885. /**
  20886. * Returns the facetLocalPositions array.
  20887. * The facet positions are expressed in the mesh local space
  20888. * @returns an array of Vector3
  20889. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20890. */
  20891. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20892. if (!this._facetPositions) {
  20893. this.updateFacetData();
  20894. }
  20895. return this._facetPositions;
  20896. };
  20897. /**
  20898. * Returns the facetLocalPartioning array
  20899. * @returns an array of array of numbers
  20900. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20901. */
  20902. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20903. if (!this._facetPartitioning) {
  20904. this.updateFacetData();
  20905. }
  20906. return this._facetPartitioning;
  20907. };
  20908. /**
  20909. * Returns the i-th facet position in the world system.
  20910. * This method allocates a new Vector3 per call
  20911. * @param i defines the facet index
  20912. * @returns a new Vector3
  20913. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20914. */
  20915. AbstractMesh.prototype.getFacetPosition = function (i) {
  20916. var pos = BABYLON.Vector3.Zero();
  20917. this.getFacetPositionToRef(i, pos);
  20918. return pos;
  20919. };
  20920. /**
  20921. * Sets the reference Vector3 with the i-th facet position in the world system
  20922. * @param i defines the facet index
  20923. * @param ref defines the target vector
  20924. * @returns the current mesh
  20925. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20926. */
  20927. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20928. var localPos = (this.getFacetLocalPositions())[i];
  20929. var world = this.getWorldMatrix();
  20930. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20931. return this;
  20932. };
  20933. /**
  20934. * Returns the i-th facet normal in the world system.
  20935. * This method allocates a new Vector3 per call
  20936. * @param i defines the facet index
  20937. * @returns a new Vector3
  20938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20939. */
  20940. AbstractMesh.prototype.getFacetNormal = function (i) {
  20941. var norm = BABYLON.Vector3.Zero();
  20942. this.getFacetNormalToRef(i, norm);
  20943. return norm;
  20944. };
  20945. /**
  20946. * Sets the reference Vector3 with the i-th facet normal in the world system
  20947. * @param i defines the facet index
  20948. * @param ref defines the target vector
  20949. * @returns the current mesh
  20950. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20951. */
  20952. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20953. var localNorm = (this.getFacetLocalNormals())[i];
  20954. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20955. return this;
  20956. };
  20957. /**
  20958. * 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)
  20959. * @param x defines x coordinate
  20960. * @param y defines y coordinate
  20961. * @param z defines z coordinate
  20962. * @returns the array of facet indexes
  20963. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20964. */
  20965. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20966. var bInfo = this.getBoundingInfo();
  20967. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20968. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20969. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20970. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20971. return null;
  20972. }
  20973. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20974. };
  20975. /**
  20976. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20977. * @param projected sets as the (x,y,z) world projection on the facet
  20978. * @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
  20979. * @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
  20980. * @param x defines x coordinate
  20981. * @param y defines y coordinate
  20982. * @param z defines z coordinate
  20983. * @returns the face index if found (or null instead)
  20984. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20985. */
  20986. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20987. if (checkFace === void 0) { checkFace = false; }
  20988. if (facing === void 0) { facing = true; }
  20989. var world = this.getWorldMatrix();
  20990. var invMat = BABYLON.Tmp.Matrix[5];
  20991. world.invertToRef(invMat);
  20992. var invVect = BABYLON.Tmp.Vector3[8];
  20993. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20994. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20995. if (projected) {
  20996. // tranform the local computed projected vector to world coordinates
  20997. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20998. }
  20999. return closest;
  21000. };
  21001. /**
  21002. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21003. * @param projected sets as the (x,y,z) local projection on the facet
  21004. * @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
  21005. * @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
  21006. * @param x defines x coordinate
  21007. * @param y defines y coordinate
  21008. * @param z defines z coordinate
  21009. * @returns the face index if found (or null instead)
  21010. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21011. */
  21012. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21013. if (checkFace === void 0) { checkFace = false; }
  21014. if (facing === void 0) { facing = true; }
  21015. var closest = null;
  21016. var tmpx = 0.0;
  21017. var tmpy = 0.0;
  21018. var tmpz = 0.0;
  21019. var d = 0.0; // tmp dot facet normal * facet position
  21020. var t0 = 0.0;
  21021. var projx = 0.0;
  21022. var projy = 0.0;
  21023. var projz = 0.0;
  21024. // Get all the facets in the same partitioning block than (x, y, z)
  21025. var facetPositions = this.getFacetLocalPositions();
  21026. var facetNormals = this.getFacetLocalNormals();
  21027. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21028. if (!facetsInBlock) {
  21029. return null;
  21030. }
  21031. // Get the closest facet to (x, y, z)
  21032. var shortest = Number.MAX_VALUE; // init distance vars
  21033. var tmpDistance = shortest;
  21034. var fib; // current facet in the block
  21035. var norm; // current facet normal
  21036. var p0; // current facet barycenter position
  21037. // loop on all the facets in the current partitioning block
  21038. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21039. fib = facetsInBlock[idx];
  21040. norm = facetNormals[fib];
  21041. p0 = facetPositions[fib];
  21042. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21043. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21044. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21045. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21046. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21047. projx = x + norm.x * t0;
  21048. projy = y + norm.y * t0;
  21049. projz = z + norm.z * t0;
  21050. tmpx = projx - x;
  21051. tmpy = projy - y;
  21052. tmpz = projz - z;
  21053. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21054. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21055. shortest = tmpDistance;
  21056. closest = fib;
  21057. if (projected) {
  21058. projected.x = projx;
  21059. projected.y = projy;
  21060. projected.z = projz;
  21061. }
  21062. }
  21063. }
  21064. }
  21065. return closest;
  21066. };
  21067. /**
  21068. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21069. * @returns the parameters
  21070. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21071. */
  21072. AbstractMesh.prototype.getFacetDataParameters = function () {
  21073. return this._facetParameters;
  21074. };
  21075. /**
  21076. * Disables the feature FacetData and frees the related memory
  21077. * @returns the current mesh
  21078. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21079. */
  21080. AbstractMesh.prototype.disableFacetData = function () {
  21081. if (this._facetDataEnabled) {
  21082. this._facetDataEnabled = false;
  21083. this._facetPositions = new Array();
  21084. this._facetNormals = new Array();
  21085. this._facetPartitioning = new Array();
  21086. this._facetParameters = null;
  21087. this._depthSortedIndices = new Uint32Array(0);
  21088. }
  21089. return this;
  21090. };
  21091. /**
  21092. * Updates the AbstractMesh indices array
  21093. * @param indices defines the data source
  21094. * @returns the current mesh
  21095. */
  21096. AbstractMesh.prototype.updateIndices = function (indices) {
  21097. return this;
  21098. };
  21099. /**
  21100. * Creates new normals data for the mesh
  21101. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21102. * @returns the current mesh
  21103. */
  21104. AbstractMesh.prototype.createNormals = function (updatable) {
  21105. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21106. var indices = this.getIndices();
  21107. var normals;
  21108. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21109. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21110. }
  21111. else {
  21112. normals = [];
  21113. }
  21114. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21115. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21116. return this;
  21117. };
  21118. /**
  21119. * Align the mesh with a normal
  21120. * @param normal defines the normal to use
  21121. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21122. * @returns the current mesh
  21123. */
  21124. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21125. if (!upDirection) {
  21126. upDirection = BABYLON.Axis.Y;
  21127. }
  21128. var axisX = BABYLON.Tmp.Vector3[0];
  21129. var axisZ = BABYLON.Tmp.Vector3[1];
  21130. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21131. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21132. if (this.rotationQuaternion) {
  21133. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21134. }
  21135. else {
  21136. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21137. }
  21138. return this;
  21139. };
  21140. /** @hidden */
  21141. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21142. var engine = this.getEngine();
  21143. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21144. this._isOccluded = false;
  21145. return;
  21146. }
  21147. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21148. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21149. if (isOcclusionQueryAvailable) {
  21150. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21151. this._isOcclusionQueryInProgress = false;
  21152. this._occlusionInternalRetryCounter = 0;
  21153. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21154. }
  21155. else {
  21156. this._occlusionInternalRetryCounter++;
  21157. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21158. this._isOcclusionQueryInProgress = false;
  21159. this._occlusionInternalRetryCounter = 0;
  21160. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21161. // if strict continue the last state of the object.
  21162. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21163. }
  21164. else {
  21165. return;
  21166. }
  21167. }
  21168. }
  21169. var scene = this.getScene();
  21170. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21171. if (!this._occlusionQuery) {
  21172. this._occlusionQuery = engine.createQuery();
  21173. }
  21174. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21175. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21176. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21177. this._isOcclusionQueryInProgress = true;
  21178. };
  21179. /** No occlusion */
  21180. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21181. /** Occlusion set to optimisitic */
  21182. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21183. /** Occlusion set to strict */
  21184. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21185. /** Use an accurante occlusion algorithm */
  21186. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21187. /** Use a conservative occlusion algorithm */
  21188. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21189. return AbstractMesh;
  21190. }(BABYLON.TransformNode));
  21191. BABYLON.AbstractMesh = AbstractMesh;
  21192. })(BABYLON || (BABYLON = {}));
  21193. //# sourceMappingURL=babylon.abstractMesh.js.map
  21194. var BABYLON;
  21195. (function (BABYLON) {
  21196. /**
  21197. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21198. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21199. * 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.
  21200. */
  21201. var Light = /** @class */ (function (_super) {
  21202. __extends(Light, _super);
  21203. /**
  21204. * Creates a Light object in the scene.
  21205. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21206. * @param name The firendly name of the light
  21207. * @param scene The scene the light belongs too
  21208. */
  21209. function Light(name, scene) {
  21210. var _this = _super.call(this, name, scene) || this;
  21211. /**
  21212. * Diffuse gives the basic color to an object.
  21213. */
  21214. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21215. /**
  21216. * Specular produces a highlight color on an object.
  21217. * Note: This is note affecting PBR materials.
  21218. */
  21219. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21220. /**
  21221. * Strength of the light.
  21222. * Note: By default it is define in the framework own unit.
  21223. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21224. */
  21225. _this.intensity = 1.0;
  21226. /**
  21227. * Defines how far from the source the light is impacting in scene units.
  21228. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21229. */
  21230. _this.range = Number.MAX_VALUE;
  21231. /**
  21232. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21233. * of light.
  21234. */
  21235. _this._photometricScale = 1.0;
  21236. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21237. _this._radius = 0.00001;
  21238. /**
  21239. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21240. * exceeding the number allowed of the materials.
  21241. */
  21242. _this.renderPriority = 0;
  21243. /**
  21244. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21245. * the current shadow generator.
  21246. */
  21247. _this.shadowEnabled = true;
  21248. _this._excludeWithLayerMask = 0;
  21249. _this._includeOnlyWithLayerMask = 0;
  21250. _this._lightmapMode = 0;
  21251. /**
  21252. * @hidden Internal use only.
  21253. */
  21254. _this._excludedMeshesIds = new Array();
  21255. /**
  21256. * @hidden Internal use only.
  21257. */
  21258. _this._includedOnlyMeshesIds = new Array();
  21259. _this.getScene().addLight(_this);
  21260. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21261. _this._buildUniformLayout();
  21262. _this.includedOnlyMeshes = new Array();
  21263. _this.excludedMeshes = new Array();
  21264. _this._resyncMeshes();
  21265. return _this;
  21266. }
  21267. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21268. /**
  21269. * If every light affecting the material is in this lightmapMode,
  21270. * material.lightmapTexture adds or multiplies
  21271. * (depends on material.useLightmapAsShadowmap)
  21272. * after every other light calculations.
  21273. */
  21274. get: function () {
  21275. return Light._LIGHTMAP_DEFAULT;
  21276. },
  21277. enumerable: true,
  21278. configurable: true
  21279. });
  21280. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21281. /**
  21282. * material.lightmapTexture as only diffuse lighting from this light
  21283. * adds only specular lighting from this light
  21284. * adds dynamic shadows
  21285. */
  21286. get: function () {
  21287. return Light._LIGHTMAP_SPECULAR;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21293. /**
  21294. * material.lightmapTexture as only lighting
  21295. * no light calculation from this light
  21296. * only adds dynamic shadows from this light
  21297. */
  21298. get: function () {
  21299. return Light._LIGHTMAP_SHADOWSONLY;
  21300. },
  21301. enumerable: true,
  21302. configurable: true
  21303. });
  21304. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21305. /**
  21306. * Each light type uses the default quantity according to its type:
  21307. * point/spot lights use luminous intensity
  21308. * directional lights use illuminance
  21309. */
  21310. get: function () {
  21311. return Light._INTENSITYMODE_AUTOMATIC;
  21312. },
  21313. enumerable: true,
  21314. configurable: true
  21315. });
  21316. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21317. /**
  21318. * lumen (lm)
  21319. */
  21320. get: function () {
  21321. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21322. },
  21323. enumerable: true,
  21324. configurable: true
  21325. });
  21326. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21327. /**
  21328. * candela (lm/sr)
  21329. */
  21330. get: function () {
  21331. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21332. },
  21333. enumerable: true,
  21334. configurable: true
  21335. });
  21336. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21337. /**
  21338. * lux (lm/m^2)
  21339. */
  21340. get: function () {
  21341. return Light._INTENSITYMODE_ILLUMINANCE;
  21342. },
  21343. enumerable: true,
  21344. configurable: true
  21345. });
  21346. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21347. /**
  21348. * nit (cd/m^2)
  21349. */
  21350. get: function () {
  21351. return Light._INTENSITYMODE_LUMINANCE;
  21352. },
  21353. enumerable: true,
  21354. configurable: true
  21355. });
  21356. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21357. /**
  21358. * Light type const id of the point light.
  21359. */
  21360. get: function () {
  21361. return Light._LIGHTTYPEID_POINTLIGHT;
  21362. },
  21363. enumerable: true,
  21364. configurable: true
  21365. });
  21366. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21367. /**
  21368. * Light type const id of the directional light.
  21369. */
  21370. get: function () {
  21371. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21372. },
  21373. enumerable: true,
  21374. configurable: true
  21375. });
  21376. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21377. /**
  21378. * Light type const id of the spot light.
  21379. */
  21380. get: function () {
  21381. return Light._LIGHTTYPEID_SPOTLIGHT;
  21382. },
  21383. enumerable: true,
  21384. configurable: true
  21385. });
  21386. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21387. /**
  21388. * Light type const id of the hemispheric light.
  21389. */
  21390. get: function () {
  21391. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21392. },
  21393. enumerable: true,
  21394. configurable: true
  21395. });
  21396. Object.defineProperty(Light.prototype, "intensityMode", {
  21397. /**
  21398. * Gets the photometric scale used to interpret the intensity.
  21399. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21400. */
  21401. get: function () {
  21402. return this._intensityMode;
  21403. },
  21404. /**
  21405. * Sets the photometric scale used to interpret the intensity.
  21406. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21407. */
  21408. set: function (value) {
  21409. this._intensityMode = value;
  21410. this._computePhotometricScale();
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. ;
  21416. ;
  21417. Object.defineProperty(Light.prototype, "radius", {
  21418. /**
  21419. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21420. */
  21421. get: function () {
  21422. return this._radius;
  21423. },
  21424. /**
  21425. * sets the light radius used by PBR Materials to simulate soft area lights.
  21426. */
  21427. set: function (value) {
  21428. this._radius = value;
  21429. this._computePhotometricScale();
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. ;
  21435. ;
  21436. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21437. /**
  21438. * Gets the only meshes impacted by this light.
  21439. */
  21440. get: function () {
  21441. return this._includedOnlyMeshes;
  21442. },
  21443. /**
  21444. * Sets the only meshes impacted by this light.
  21445. */
  21446. set: function (value) {
  21447. this._includedOnlyMeshes = value;
  21448. this._hookArrayForIncludedOnly(value);
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21454. /**
  21455. * Gets the meshes not impacted by this light.
  21456. */
  21457. get: function () {
  21458. return this._excludedMeshes;
  21459. },
  21460. /**
  21461. * Sets the meshes not impacted by this light.
  21462. */
  21463. set: function (value) {
  21464. this._excludedMeshes = value;
  21465. this._hookArrayForExcluded(value);
  21466. },
  21467. enumerable: true,
  21468. configurable: true
  21469. });
  21470. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21471. /**
  21472. * Gets the layer id use to find what meshes are not impacted by the light.
  21473. * Inactive if 0
  21474. */
  21475. get: function () {
  21476. return this._excludeWithLayerMask;
  21477. },
  21478. /**
  21479. * Sets the layer id use to find what meshes are not impacted by the light.
  21480. * Inactive if 0
  21481. */
  21482. set: function (value) {
  21483. this._excludeWithLayerMask = value;
  21484. this._resyncMeshes();
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21490. /**
  21491. * Gets the layer id use to find what meshes are impacted by the light.
  21492. * Inactive if 0
  21493. */
  21494. get: function () {
  21495. return this._includeOnlyWithLayerMask;
  21496. },
  21497. /**
  21498. * Sets the layer id use to find what meshes are impacted by the light.
  21499. * Inactive if 0
  21500. */
  21501. set: function (value) {
  21502. this._includeOnlyWithLayerMask = value;
  21503. this._resyncMeshes();
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Light.prototype, "lightmapMode", {
  21509. /**
  21510. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21511. */
  21512. get: function () {
  21513. return this._lightmapMode;
  21514. },
  21515. /**
  21516. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21517. */
  21518. set: function (value) {
  21519. if (this._lightmapMode === value) {
  21520. return;
  21521. }
  21522. this._lightmapMode = value;
  21523. this._markMeshesAsLightDirty();
  21524. },
  21525. enumerable: true,
  21526. configurable: true
  21527. });
  21528. /**
  21529. * Returns the string "Light".
  21530. * @returns the class name
  21531. */
  21532. Light.prototype.getClassName = function () {
  21533. return "Light";
  21534. };
  21535. /**
  21536. * Converts the light information to a readable string for debug purpose.
  21537. * @param fullDetails Supports for multiple levels of logging within scene loading
  21538. * @returns the human readable light info
  21539. */
  21540. Light.prototype.toString = function (fullDetails) {
  21541. var ret = "Name: " + this.name;
  21542. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21543. if (this.animations) {
  21544. for (var i = 0; i < this.animations.length; i++) {
  21545. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21546. }
  21547. }
  21548. if (fullDetails) {
  21549. }
  21550. return ret;
  21551. };
  21552. /**
  21553. * Set the enabled state of this node.
  21554. * @param value - the new enabled state
  21555. */
  21556. Light.prototype.setEnabled = function (value) {
  21557. _super.prototype.setEnabled.call(this, value);
  21558. this._resyncMeshes();
  21559. };
  21560. /**
  21561. * Returns the Light associated shadow generator if any.
  21562. * @return the associated shadow generator.
  21563. */
  21564. Light.prototype.getShadowGenerator = function () {
  21565. return this._shadowGenerator;
  21566. };
  21567. /**
  21568. * Returns a Vector3, the absolute light position in the World.
  21569. * @returns the world space position of the light
  21570. */
  21571. Light.prototype.getAbsolutePosition = function () {
  21572. return BABYLON.Vector3.Zero();
  21573. };
  21574. /**
  21575. * Specifies if the light will affect the passed mesh.
  21576. * @param mesh The mesh to test against the light
  21577. * @return true the mesh is affected otherwise, false.
  21578. */
  21579. Light.prototype.canAffectMesh = function (mesh) {
  21580. if (!mesh) {
  21581. return true;
  21582. }
  21583. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21584. return false;
  21585. }
  21586. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21587. return false;
  21588. }
  21589. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21590. return false;
  21591. }
  21592. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21593. return false;
  21594. }
  21595. return true;
  21596. };
  21597. /**
  21598. * Computes and Returns the light World matrix.
  21599. * @returns the world matrix
  21600. */
  21601. Light.prototype.getWorldMatrix = function () {
  21602. this._currentRenderId = this.getScene().getRenderId();
  21603. this._childRenderId = this._currentRenderId;
  21604. var worldMatrix = this._getWorldMatrix();
  21605. if (this.parent && this.parent.getWorldMatrix) {
  21606. if (!this._parentedWorldMatrix) {
  21607. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21608. }
  21609. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21610. this._markSyncedWithParent();
  21611. return this._parentedWorldMatrix;
  21612. }
  21613. return worldMatrix;
  21614. };
  21615. /**
  21616. * Sort function to order lights for rendering.
  21617. * @param a First Light object to compare to second.
  21618. * @param b Second Light object to compare first.
  21619. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21620. */
  21621. Light.CompareLightsPriority = function (a, b) {
  21622. //shadow-casting lights have priority over non-shadow-casting lights
  21623. //the renderPrioirty is a secondary sort criterion
  21624. if (a.shadowEnabled !== b.shadowEnabled) {
  21625. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21626. }
  21627. return b.renderPriority - a.renderPriority;
  21628. };
  21629. /**
  21630. * Releases resources associated with this node.
  21631. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21632. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21633. */
  21634. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21635. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21636. if (this._shadowGenerator) {
  21637. this._shadowGenerator.dispose();
  21638. this._shadowGenerator = null;
  21639. }
  21640. // Animations
  21641. this.getScene().stopAnimation(this);
  21642. // Remove from meshes
  21643. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21644. var mesh = _a[_i];
  21645. mesh._removeLightSource(this);
  21646. }
  21647. this._uniformBuffer.dispose();
  21648. // Remove from scene
  21649. this.getScene().removeLight(this);
  21650. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21651. };
  21652. /**
  21653. * Returns the light type ID (integer).
  21654. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21655. */
  21656. Light.prototype.getTypeID = function () {
  21657. return 0;
  21658. };
  21659. /**
  21660. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21661. * @returns the scaled intensity in intensity mode unit
  21662. */
  21663. Light.prototype.getScaledIntensity = function () {
  21664. return this._photometricScale * this.intensity;
  21665. };
  21666. /**
  21667. * Returns a new Light object, named "name", from the current one.
  21668. * @param name The name of the cloned light
  21669. * @returns the new created light
  21670. */
  21671. Light.prototype.clone = function (name) {
  21672. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21673. if (!constructor) {
  21674. return null;
  21675. }
  21676. return BABYLON.SerializationHelper.Clone(constructor, this);
  21677. };
  21678. /**
  21679. * Serializes the current light into a Serialization object.
  21680. * @returns the serialized object.
  21681. */
  21682. Light.prototype.serialize = function () {
  21683. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21684. // Type
  21685. serializationObject.type = this.getTypeID();
  21686. // Parent
  21687. if (this.parent) {
  21688. serializationObject.parentId = this.parent.id;
  21689. }
  21690. // Inclusion / exclusions
  21691. if (this.excludedMeshes.length > 0) {
  21692. serializationObject.excludedMeshesIds = [];
  21693. this.excludedMeshes.forEach(function (mesh) {
  21694. serializationObject.excludedMeshesIds.push(mesh.id);
  21695. });
  21696. }
  21697. if (this.includedOnlyMeshes.length > 0) {
  21698. serializationObject.includedOnlyMeshesIds = [];
  21699. this.includedOnlyMeshes.forEach(function (mesh) {
  21700. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21701. });
  21702. }
  21703. // Animations
  21704. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21705. serializationObject.ranges = this.serializeAnimationRanges();
  21706. return serializationObject;
  21707. };
  21708. /**
  21709. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21710. * This new light is named "name" and added to the passed scene.
  21711. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21712. * @param name The friendly name of the light
  21713. * @param scene The scene the new light will belong to
  21714. * @returns the constructor function
  21715. */
  21716. Light.GetConstructorFromName = function (type, name, scene) {
  21717. switch (type) {
  21718. case 0:
  21719. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21720. case 1:
  21721. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21722. case 2:
  21723. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21724. case 3:
  21725. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21726. }
  21727. return null;
  21728. };
  21729. /**
  21730. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21731. * @param parsedLight The JSON representation of the light
  21732. * @param scene The scene to create the parsed light in
  21733. * @returns the created light after parsing
  21734. */
  21735. Light.Parse = function (parsedLight, scene) {
  21736. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21737. if (!constructor) {
  21738. return null;
  21739. }
  21740. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21741. // Inclusion / exclusions
  21742. if (parsedLight.excludedMeshesIds) {
  21743. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21744. }
  21745. if (parsedLight.includedOnlyMeshesIds) {
  21746. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21747. }
  21748. // Parent
  21749. if (parsedLight.parentId) {
  21750. light._waitingParentId = parsedLight.parentId;
  21751. }
  21752. // Animations
  21753. if (parsedLight.animations) {
  21754. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21755. var parsedAnimation = parsedLight.animations[animationIndex];
  21756. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21757. }
  21758. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21759. }
  21760. if (parsedLight.autoAnimate) {
  21761. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21762. }
  21763. return light;
  21764. };
  21765. Light.prototype._hookArrayForExcluded = function (array) {
  21766. var _this = this;
  21767. var oldPush = array.push;
  21768. array.push = function () {
  21769. var items = [];
  21770. for (var _i = 0; _i < arguments.length; _i++) {
  21771. items[_i] = arguments[_i];
  21772. }
  21773. var result = oldPush.apply(array, items);
  21774. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21775. var item = items_1[_a];
  21776. item._resyncLighSource(_this);
  21777. }
  21778. return result;
  21779. };
  21780. var oldSplice = array.splice;
  21781. array.splice = function (index, deleteCount) {
  21782. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21783. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21784. var item = deleted_1[_i];
  21785. item._resyncLighSource(_this);
  21786. }
  21787. return deleted;
  21788. };
  21789. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21790. var item = array_1[_i];
  21791. item._resyncLighSource(this);
  21792. }
  21793. };
  21794. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21795. var _this = this;
  21796. var oldPush = array.push;
  21797. array.push = function () {
  21798. var items = [];
  21799. for (var _i = 0; _i < arguments.length; _i++) {
  21800. items[_i] = arguments[_i];
  21801. }
  21802. var result = oldPush.apply(array, items);
  21803. _this._resyncMeshes();
  21804. return result;
  21805. };
  21806. var oldSplice = array.splice;
  21807. array.splice = function (index, deleteCount) {
  21808. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21809. _this._resyncMeshes();
  21810. return deleted;
  21811. };
  21812. this._resyncMeshes();
  21813. };
  21814. Light.prototype._resyncMeshes = function () {
  21815. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21816. var mesh = _a[_i];
  21817. mesh._resyncLighSource(this);
  21818. }
  21819. };
  21820. /**
  21821. * Forces the meshes to update their light related information in their rendering used effects
  21822. * @hidden Internal Use Only
  21823. */
  21824. Light.prototype._markMeshesAsLightDirty = function () {
  21825. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21826. var mesh = _a[_i];
  21827. if (mesh._lightSources.indexOf(this) !== -1) {
  21828. mesh._markSubMeshesAsLightDirty();
  21829. }
  21830. }
  21831. };
  21832. /**
  21833. * Recomputes the cached photometric scale if needed.
  21834. */
  21835. Light.prototype._computePhotometricScale = function () {
  21836. this._photometricScale = this._getPhotometricScale();
  21837. this.getScene().resetCachedMaterial();
  21838. };
  21839. /**
  21840. * Returns the Photometric Scale according to the light type and intensity mode.
  21841. */
  21842. Light.prototype._getPhotometricScale = function () {
  21843. var photometricScale = 0.0;
  21844. var lightTypeID = this.getTypeID();
  21845. //get photometric mode
  21846. var photometricMode = this.intensityMode;
  21847. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21848. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21849. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21850. }
  21851. else {
  21852. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21853. }
  21854. }
  21855. //compute photometric scale
  21856. switch (lightTypeID) {
  21857. case Light.LIGHTTYPEID_POINTLIGHT:
  21858. case Light.LIGHTTYPEID_SPOTLIGHT:
  21859. switch (photometricMode) {
  21860. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21861. photometricScale = 1.0 / (4.0 * Math.PI);
  21862. break;
  21863. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21864. photometricScale = 1.0;
  21865. break;
  21866. case Light.INTENSITYMODE_LUMINANCE:
  21867. photometricScale = this.radius * this.radius;
  21868. break;
  21869. }
  21870. break;
  21871. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21872. switch (photometricMode) {
  21873. case Light.INTENSITYMODE_ILLUMINANCE:
  21874. photometricScale = 1.0;
  21875. break;
  21876. case Light.INTENSITYMODE_LUMINANCE:
  21877. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21878. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21879. var apexAngleRadians = this.radius;
  21880. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21881. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21882. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21883. photometricScale = solidAngle;
  21884. break;
  21885. }
  21886. break;
  21887. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21888. // No fall off in hemisperic light.
  21889. photometricScale = 1.0;
  21890. break;
  21891. }
  21892. return photometricScale;
  21893. };
  21894. /**
  21895. * Reorder the light in the scene according to their defined priority.
  21896. * @hidden Internal Use Only
  21897. */
  21898. Light.prototype._reorderLightsInScene = function () {
  21899. var scene = this.getScene();
  21900. if (this._renderPriority != 0) {
  21901. scene.requireLightSorting = true;
  21902. }
  21903. this.getScene().sortLightsByPriority();
  21904. };
  21905. //lightmapMode Consts
  21906. Light._LIGHTMAP_DEFAULT = 0;
  21907. Light._LIGHTMAP_SPECULAR = 1;
  21908. Light._LIGHTMAP_SHADOWSONLY = 2;
  21909. // Intensity Mode Consts
  21910. Light._INTENSITYMODE_AUTOMATIC = 0;
  21911. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21912. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21913. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21914. Light._INTENSITYMODE_LUMINANCE = 4;
  21915. // Light types ids const.
  21916. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21917. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21918. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21919. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21920. __decorate([
  21921. BABYLON.serializeAsColor3()
  21922. ], Light.prototype, "diffuse", void 0);
  21923. __decorate([
  21924. BABYLON.serializeAsColor3()
  21925. ], Light.prototype, "specular", void 0);
  21926. __decorate([
  21927. BABYLON.serialize()
  21928. ], Light.prototype, "intensity", void 0);
  21929. __decorate([
  21930. BABYLON.serialize()
  21931. ], Light.prototype, "range", void 0);
  21932. __decorate([
  21933. BABYLON.serialize()
  21934. ], Light.prototype, "intensityMode", null);
  21935. __decorate([
  21936. BABYLON.serialize()
  21937. ], Light.prototype, "radius", null);
  21938. __decorate([
  21939. BABYLON.serialize()
  21940. ], Light.prototype, "_renderPriority", void 0);
  21941. __decorate([
  21942. BABYLON.expandToProperty("_reorderLightsInScene")
  21943. ], Light.prototype, "renderPriority", void 0);
  21944. __decorate([
  21945. BABYLON.serialize()
  21946. ], Light.prototype, "shadowEnabled", void 0);
  21947. __decorate([
  21948. BABYLON.serialize("excludeWithLayerMask")
  21949. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21950. __decorate([
  21951. BABYLON.serialize("includeOnlyWithLayerMask")
  21952. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21953. __decorate([
  21954. BABYLON.serialize("lightmapMode")
  21955. ], Light.prototype, "_lightmapMode", void 0);
  21956. return Light;
  21957. }(BABYLON.Node));
  21958. BABYLON.Light = Light;
  21959. })(BABYLON || (BABYLON = {}));
  21960. //# sourceMappingURL=babylon.light.js.map
  21961. var BABYLON;
  21962. (function (BABYLON) {
  21963. var Camera = /** @class */ (function (_super) {
  21964. __extends(Camera, _super);
  21965. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21966. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21967. var _this = _super.call(this, name, scene) || this;
  21968. /**
  21969. * The vector the camera should consider as up.
  21970. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21971. */
  21972. _this.upVector = BABYLON.Vector3.Up();
  21973. _this.orthoLeft = null;
  21974. _this.orthoRight = null;
  21975. _this.orthoBottom = null;
  21976. _this.orthoTop = null;
  21977. /**
  21978. * FOV is set in Radians. (default is 0.8)
  21979. */
  21980. _this.fov = 0.8;
  21981. _this.minZ = 1;
  21982. _this.maxZ = 10000.0;
  21983. _this.inertia = 0.9;
  21984. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21985. _this.isIntermediate = false;
  21986. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21987. /**
  21988. * Restricts the camera to viewing objects with the same layerMask.
  21989. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21990. */
  21991. _this.layerMask = 0x0FFFFFFF;
  21992. /**
  21993. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21994. */
  21995. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21996. // Camera rig members
  21997. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21998. _this._rigCameras = new Array();
  21999. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22000. _this._skipRendering = false;
  22001. _this.customRenderTargets = new Array();
  22002. // Observables
  22003. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22004. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22005. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22006. _this.onRestoreStateObservable = new BABYLON.Observable();
  22007. // Cache
  22008. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22009. _this._projectionMatrix = new BABYLON.Matrix();
  22010. _this._doNotComputeProjectionMatrix = false;
  22011. _this._worldMatrix = BABYLON.Matrix.Identity();
  22012. _this._postProcesses = new Array();
  22013. _this._transformMatrix = BABYLON.Matrix.Zero();
  22014. _this._activeMeshes = new BABYLON.SmartArray(256);
  22015. _this._globalPosition = BABYLON.Vector3.Zero();
  22016. _this._refreshFrustumPlanes = true;
  22017. _this.getScene().addCamera(_this);
  22018. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22019. _this.getScene().activeCamera = _this;
  22020. }
  22021. _this.position = position;
  22022. return _this;
  22023. }
  22024. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22025. get: function () {
  22026. return Camera._PERSPECTIVE_CAMERA;
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22032. get: function () {
  22033. return Camera._ORTHOGRAPHIC_CAMERA;
  22034. },
  22035. enumerable: true,
  22036. configurable: true
  22037. });
  22038. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22039. /**
  22040. * This is the default FOV mode for perspective cameras.
  22041. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22042. *
  22043. */
  22044. get: function () {
  22045. return Camera._FOVMODE_VERTICAL_FIXED;
  22046. },
  22047. enumerable: true,
  22048. configurable: true
  22049. });
  22050. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22051. /**
  22052. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22053. *
  22054. */
  22055. get: function () {
  22056. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22062. get: function () {
  22063. return Camera._RIG_MODE_NONE;
  22064. },
  22065. enumerable: true,
  22066. configurable: true
  22067. });
  22068. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22069. get: function () {
  22070. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22076. get: function () {
  22077. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22078. },
  22079. enumerable: true,
  22080. configurable: true
  22081. });
  22082. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22083. get: function () {
  22084. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22090. get: function () {
  22091. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22097. get: function () {
  22098. return Camera._RIG_MODE_VR;
  22099. },
  22100. enumerable: true,
  22101. configurable: true
  22102. });
  22103. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22104. get: function () {
  22105. return Camera._RIG_MODE_WEBVR;
  22106. },
  22107. enumerable: true,
  22108. configurable: true
  22109. });
  22110. /**
  22111. * Store current camera state (fov, position, etc..)
  22112. */
  22113. Camera.prototype.storeState = function () {
  22114. this._stateStored = true;
  22115. this._storedFov = this.fov;
  22116. return this;
  22117. };
  22118. /**
  22119. * Restores the camera state values if it has been stored. You must call storeState() first
  22120. */
  22121. Camera.prototype._restoreStateValues = function () {
  22122. if (!this._stateStored) {
  22123. return false;
  22124. }
  22125. this.fov = this._storedFov;
  22126. return true;
  22127. };
  22128. /**
  22129. * Restored camera state. You must call storeState() first
  22130. */
  22131. Camera.prototype.restoreState = function () {
  22132. if (this._restoreStateValues()) {
  22133. this.onRestoreStateObservable.notifyObservers(this);
  22134. return true;
  22135. }
  22136. return false;
  22137. };
  22138. Camera.prototype.getClassName = function () {
  22139. return "Camera";
  22140. };
  22141. /**
  22142. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22143. */
  22144. Camera.prototype.toString = function (fullDetails) {
  22145. var ret = "Name: " + this.name;
  22146. ret += ", type: " + this.getClassName();
  22147. if (this.animations) {
  22148. for (var i = 0; i < this.animations.length; i++) {
  22149. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22150. }
  22151. }
  22152. if (fullDetails) {
  22153. }
  22154. return ret;
  22155. };
  22156. Object.defineProperty(Camera.prototype, "globalPosition", {
  22157. get: function () {
  22158. return this._globalPosition;
  22159. },
  22160. enumerable: true,
  22161. configurable: true
  22162. });
  22163. Camera.prototype.getActiveMeshes = function () {
  22164. return this._activeMeshes;
  22165. };
  22166. Camera.prototype.isActiveMesh = function (mesh) {
  22167. return (this._activeMeshes.indexOf(mesh) !== -1);
  22168. };
  22169. /**
  22170. * Is this camera ready to be used/rendered
  22171. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22172. * @return true if the camera is ready
  22173. */
  22174. Camera.prototype.isReady = function (completeCheck) {
  22175. if (completeCheck === void 0) { completeCheck = false; }
  22176. if (completeCheck) {
  22177. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22178. var pp = _a[_i];
  22179. if (pp && !pp.isReady()) {
  22180. return false;
  22181. }
  22182. }
  22183. }
  22184. return _super.prototype.isReady.call(this, completeCheck);
  22185. };
  22186. //Cache
  22187. Camera.prototype._initCache = function () {
  22188. _super.prototype._initCache.call(this);
  22189. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22190. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22191. this._cache.mode = undefined;
  22192. this._cache.minZ = undefined;
  22193. this._cache.maxZ = undefined;
  22194. this._cache.fov = undefined;
  22195. this._cache.fovMode = undefined;
  22196. this._cache.aspectRatio = undefined;
  22197. this._cache.orthoLeft = undefined;
  22198. this._cache.orthoRight = undefined;
  22199. this._cache.orthoBottom = undefined;
  22200. this._cache.orthoTop = undefined;
  22201. this._cache.renderWidth = undefined;
  22202. this._cache.renderHeight = undefined;
  22203. };
  22204. Camera.prototype._updateCache = function (ignoreParentClass) {
  22205. if (!ignoreParentClass) {
  22206. _super.prototype._updateCache.call(this);
  22207. }
  22208. this._cache.position.copyFrom(this.position);
  22209. this._cache.upVector.copyFrom(this.upVector);
  22210. };
  22211. // Synchronized
  22212. Camera.prototype._isSynchronized = function () {
  22213. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22214. };
  22215. Camera.prototype._isSynchronizedViewMatrix = function () {
  22216. if (!_super.prototype._isSynchronized.call(this))
  22217. return false;
  22218. return this._cache.position.equals(this.position)
  22219. && this._cache.upVector.equals(this.upVector)
  22220. && this.isSynchronizedWithParent();
  22221. };
  22222. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22223. var check = this._cache.mode === this.mode
  22224. && this._cache.minZ === this.minZ
  22225. && this._cache.maxZ === this.maxZ;
  22226. if (!check) {
  22227. return false;
  22228. }
  22229. var engine = this.getEngine();
  22230. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22231. check = this._cache.fov === this.fov
  22232. && this._cache.fovMode === this.fovMode
  22233. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22234. }
  22235. else {
  22236. check = this._cache.orthoLeft === this.orthoLeft
  22237. && this._cache.orthoRight === this.orthoRight
  22238. && this._cache.orthoBottom === this.orthoBottom
  22239. && this._cache.orthoTop === this.orthoTop
  22240. && this._cache.renderWidth === engine.getRenderWidth()
  22241. && this._cache.renderHeight === engine.getRenderHeight();
  22242. }
  22243. return check;
  22244. };
  22245. // Controls
  22246. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22247. };
  22248. Camera.prototype.detachControl = function (element) {
  22249. };
  22250. Camera.prototype.update = function () {
  22251. this._checkInputs();
  22252. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22253. this._updateRigCameras();
  22254. }
  22255. };
  22256. Camera.prototype._checkInputs = function () {
  22257. this.onAfterCheckInputsObservable.notifyObservers(this);
  22258. };
  22259. Object.defineProperty(Camera.prototype, "rigCameras", {
  22260. get: function () {
  22261. return this._rigCameras;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22267. get: function () {
  22268. return this._rigPostProcess;
  22269. },
  22270. enumerable: true,
  22271. configurable: true
  22272. });
  22273. /**
  22274. * Internal, gets the first post proces.
  22275. * @returns the first post process to be run on this camera.
  22276. */
  22277. Camera.prototype._getFirstPostProcess = function () {
  22278. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22279. if (this._postProcesses[ppIndex] !== null) {
  22280. return this._postProcesses[ppIndex];
  22281. }
  22282. }
  22283. return null;
  22284. };
  22285. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22286. // invalidate framebuffer
  22287. var firstPostProcess = this._getFirstPostProcess();
  22288. if (firstPostProcess) {
  22289. firstPostProcess.markTextureDirty();
  22290. }
  22291. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22292. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22293. var cam = this._rigCameras[i];
  22294. var rigPostProcess = cam._rigPostProcess;
  22295. // for VR rig, there does not have to be a post process
  22296. if (rigPostProcess) {
  22297. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22298. if (isPass) {
  22299. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22300. cam.isIntermediate = this._postProcesses.length === 0;
  22301. }
  22302. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22303. rigPostProcess.markTextureDirty();
  22304. }
  22305. else {
  22306. cam._postProcesses = this._postProcesses.slice(0);
  22307. }
  22308. }
  22309. };
  22310. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22311. if (insertAt === void 0) { insertAt = null; }
  22312. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22313. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22314. return 0;
  22315. }
  22316. if (insertAt == null || insertAt < 0) {
  22317. this._postProcesses.push(postProcess);
  22318. }
  22319. else if (this._postProcesses[insertAt] === null) {
  22320. this._postProcesses[insertAt] = postProcess;
  22321. }
  22322. else {
  22323. this._postProcesses.splice(insertAt, 0, postProcess);
  22324. }
  22325. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22326. return this._postProcesses.indexOf(postProcess);
  22327. };
  22328. Camera.prototype.detachPostProcess = function (postProcess) {
  22329. var idx = this._postProcesses.indexOf(postProcess);
  22330. if (idx !== -1) {
  22331. this._postProcesses[idx] = null;
  22332. }
  22333. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22334. };
  22335. Camera.prototype.getWorldMatrix = function () {
  22336. if (this._isSynchronizedViewMatrix()) {
  22337. return this._worldMatrix;
  22338. }
  22339. // Getting the the view matrix will also compute the world matrix.
  22340. this.getViewMatrix();
  22341. return this._worldMatrix;
  22342. };
  22343. Camera.prototype._getViewMatrix = function () {
  22344. return BABYLON.Matrix.Identity();
  22345. };
  22346. Camera.prototype.getViewMatrix = function (force) {
  22347. if (!force && this._isSynchronizedViewMatrix()) {
  22348. return this._computedViewMatrix;
  22349. }
  22350. this.updateCache();
  22351. this._computedViewMatrix = this._getViewMatrix();
  22352. this._currentRenderId = this.getScene().getRenderId();
  22353. this._childRenderId = this._currentRenderId;
  22354. this._refreshFrustumPlanes = true;
  22355. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22356. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22357. }
  22358. this.onViewMatrixChangedObservable.notifyObservers(this);
  22359. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22360. return this._computedViewMatrix;
  22361. };
  22362. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22363. this._doNotComputeProjectionMatrix = true;
  22364. if (projection !== undefined) {
  22365. this._projectionMatrix = projection;
  22366. }
  22367. };
  22368. ;
  22369. Camera.prototype.unfreezeProjectionMatrix = function () {
  22370. this._doNotComputeProjectionMatrix = false;
  22371. };
  22372. ;
  22373. Camera.prototype.getProjectionMatrix = function (force) {
  22374. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22375. return this._projectionMatrix;
  22376. }
  22377. // Cache
  22378. this._cache.mode = this.mode;
  22379. this._cache.minZ = this.minZ;
  22380. this._cache.maxZ = this.maxZ;
  22381. // Matrix
  22382. this._refreshFrustumPlanes = true;
  22383. var engine = this.getEngine();
  22384. var scene = this.getScene();
  22385. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22386. this._cache.fov = this.fov;
  22387. this._cache.fovMode = this.fovMode;
  22388. this._cache.aspectRatio = engine.getAspectRatio(this);
  22389. if (this.minZ <= 0) {
  22390. this.minZ = 0.1;
  22391. }
  22392. if (scene.useRightHandedSystem) {
  22393. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22394. }
  22395. else {
  22396. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22397. }
  22398. }
  22399. else {
  22400. var halfWidth = engine.getRenderWidth() / 2.0;
  22401. var halfHeight = engine.getRenderHeight() / 2.0;
  22402. if (scene.useRightHandedSystem) {
  22403. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22404. }
  22405. else {
  22406. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22407. }
  22408. this._cache.orthoLeft = this.orthoLeft;
  22409. this._cache.orthoRight = this.orthoRight;
  22410. this._cache.orthoBottom = this.orthoBottom;
  22411. this._cache.orthoTop = this.orthoTop;
  22412. this._cache.renderWidth = engine.getRenderWidth();
  22413. this._cache.renderHeight = engine.getRenderHeight();
  22414. }
  22415. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22416. return this._projectionMatrix;
  22417. };
  22418. Camera.prototype.getTranformationMatrix = function () {
  22419. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22420. return this._transformMatrix;
  22421. };
  22422. Camera.prototype.updateFrustumPlanes = function () {
  22423. if (!this._refreshFrustumPlanes) {
  22424. return;
  22425. }
  22426. this.getTranformationMatrix();
  22427. if (!this._frustumPlanes) {
  22428. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22429. }
  22430. else {
  22431. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22432. }
  22433. this._refreshFrustumPlanes = false;
  22434. };
  22435. Camera.prototype.isInFrustum = function (target) {
  22436. this.updateFrustumPlanes();
  22437. return target.isInFrustum(this._frustumPlanes);
  22438. };
  22439. Camera.prototype.isCompletelyInFrustum = function (target) {
  22440. this.updateFrustumPlanes();
  22441. return target.isCompletelyInFrustum(this._frustumPlanes);
  22442. };
  22443. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22444. if (length === void 0) { length = 100; }
  22445. if (!transform) {
  22446. transform = this.getWorldMatrix();
  22447. }
  22448. if (!origin) {
  22449. origin = this.position;
  22450. }
  22451. var forward = new BABYLON.Vector3(0, 0, 1);
  22452. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22453. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22454. return new BABYLON.Ray(origin, direction, length);
  22455. };
  22456. /**
  22457. * Releases resources associated with this node.
  22458. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22459. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22460. */
  22461. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22462. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22463. // Observables
  22464. this.onViewMatrixChangedObservable.clear();
  22465. this.onProjectionMatrixChangedObservable.clear();
  22466. this.onAfterCheckInputsObservable.clear();
  22467. this.onRestoreStateObservable.clear();
  22468. // Inputs
  22469. if (this.inputs) {
  22470. this.inputs.clear();
  22471. }
  22472. // Animations
  22473. this.getScene().stopAnimation(this);
  22474. // Remove from scene
  22475. this.getScene().removeCamera(this);
  22476. while (this._rigCameras.length > 0) {
  22477. var camera = this._rigCameras.pop();
  22478. if (camera) {
  22479. camera.dispose();
  22480. }
  22481. }
  22482. // Postprocesses
  22483. if (this._rigPostProcess) {
  22484. this._rigPostProcess.dispose(this);
  22485. this._rigPostProcess = null;
  22486. this._postProcesses = [];
  22487. }
  22488. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22489. this._rigPostProcess = null;
  22490. this._postProcesses = [];
  22491. }
  22492. else {
  22493. var i = this._postProcesses.length;
  22494. while (--i >= 0) {
  22495. var postProcess = this._postProcesses[i];
  22496. if (postProcess) {
  22497. postProcess.dispose(this);
  22498. }
  22499. }
  22500. }
  22501. // Render targets
  22502. var i = this.customRenderTargets.length;
  22503. while (--i >= 0) {
  22504. this.customRenderTargets[i].dispose();
  22505. }
  22506. this.customRenderTargets = [];
  22507. // Active Meshes
  22508. this._activeMeshes.dispose();
  22509. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22510. };
  22511. Object.defineProperty(Camera.prototype, "leftCamera", {
  22512. // ---- Camera rigs section ----
  22513. get: function () {
  22514. if (this._rigCameras.length < 1) {
  22515. return null;
  22516. }
  22517. return this._rigCameras[0];
  22518. },
  22519. enumerable: true,
  22520. configurable: true
  22521. });
  22522. Object.defineProperty(Camera.prototype, "rightCamera", {
  22523. get: function () {
  22524. if (this._rigCameras.length < 2) {
  22525. return null;
  22526. }
  22527. return this._rigCameras[1];
  22528. },
  22529. enumerable: true,
  22530. configurable: true
  22531. });
  22532. Camera.prototype.getLeftTarget = function () {
  22533. if (this._rigCameras.length < 1) {
  22534. return null;
  22535. }
  22536. return this._rigCameras[0].getTarget();
  22537. };
  22538. Camera.prototype.getRightTarget = function () {
  22539. if (this._rigCameras.length < 2) {
  22540. return null;
  22541. }
  22542. return this._rigCameras[1].getTarget();
  22543. };
  22544. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22545. if (this.cameraRigMode === mode) {
  22546. return;
  22547. }
  22548. while (this._rigCameras.length > 0) {
  22549. var camera = this._rigCameras.pop();
  22550. if (camera) {
  22551. camera.dispose();
  22552. }
  22553. }
  22554. this.cameraRigMode = mode;
  22555. this._cameraRigParams = {};
  22556. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22557. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22558. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22559. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22560. // create the rig cameras, unless none
  22561. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22562. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22563. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22564. if (leftCamera && rightCamera) {
  22565. this._rigCameras.push(leftCamera);
  22566. this._rigCameras.push(rightCamera);
  22567. }
  22568. }
  22569. switch (this.cameraRigMode) {
  22570. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22571. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22572. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22573. break;
  22574. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22575. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22576. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22577. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22578. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22579. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22580. break;
  22581. case Camera.RIG_MODE_VR:
  22582. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22583. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22584. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22585. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22586. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22587. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22588. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22589. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22590. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22591. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22592. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22593. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22594. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22595. if (metrics.compensateDistortion) {
  22596. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22597. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22598. }
  22599. break;
  22600. case Camera.RIG_MODE_WEBVR:
  22601. if (rigParams.vrDisplay) {
  22602. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22603. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22604. //Left eye
  22605. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22606. this._rigCameras[0].setCameraRigParameter("left", true);
  22607. //leaving this for future reference
  22608. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22609. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22610. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22611. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22612. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22613. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22614. this._rigCameras[0].parent = this;
  22615. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22616. //Right eye
  22617. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22618. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22619. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22620. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22621. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22622. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22623. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22624. this._rigCameras[1].parent = this;
  22625. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22626. if (Camera.UseAlternateWebVRRendering) {
  22627. this._rigCameras[1]._skipRendering = true;
  22628. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22629. }
  22630. }
  22631. break;
  22632. }
  22633. this._cascadePostProcessesToRigCams();
  22634. this.update();
  22635. };
  22636. Camera.prototype._getVRProjectionMatrix = function () {
  22637. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22638. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22639. return this._projectionMatrix;
  22640. };
  22641. Camera.prototype._updateCameraRotationMatrix = function () {
  22642. //Here for WebVR
  22643. };
  22644. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22645. //Here for WebVR
  22646. };
  22647. /**
  22648. * This function MUST be overwritten by the different WebVR cameras available.
  22649. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22650. */
  22651. Camera.prototype._getWebVRProjectionMatrix = function () {
  22652. return BABYLON.Matrix.Identity();
  22653. };
  22654. /**
  22655. * This function MUST be overwritten by the different WebVR cameras available.
  22656. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22657. */
  22658. Camera.prototype._getWebVRViewMatrix = function () {
  22659. return BABYLON.Matrix.Identity();
  22660. };
  22661. Camera.prototype.setCameraRigParameter = function (name, value) {
  22662. if (!this._cameraRigParams) {
  22663. this._cameraRigParams = {};
  22664. }
  22665. this._cameraRigParams[name] = value;
  22666. //provisionnally:
  22667. if (name === "interaxialDistance") {
  22668. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22669. }
  22670. };
  22671. /**
  22672. * needs to be overridden by children so sub has required properties to be copied
  22673. */
  22674. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22675. return null;
  22676. };
  22677. /**
  22678. * May need to be overridden by children
  22679. */
  22680. Camera.prototype._updateRigCameras = function () {
  22681. for (var i = 0; i < this._rigCameras.length; i++) {
  22682. this._rigCameras[i].minZ = this.minZ;
  22683. this._rigCameras[i].maxZ = this.maxZ;
  22684. this._rigCameras[i].fov = this.fov;
  22685. }
  22686. // only update viewport when ANAGLYPH
  22687. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22688. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22689. }
  22690. };
  22691. Camera.prototype._setupInputs = function () {
  22692. };
  22693. Camera.prototype.serialize = function () {
  22694. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22695. // Type
  22696. serializationObject.type = this.getClassName();
  22697. // Parent
  22698. if (this.parent) {
  22699. serializationObject.parentId = this.parent.id;
  22700. }
  22701. if (this.inputs) {
  22702. this.inputs.serialize(serializationObject);
  22703. }
  22704. // Animations
  22705. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22706. serializationObject.ranges = this.serializeAnimationRanges();
  22707. return serializationObject;
  22708. };
  22709. Camera.prototype.clone = function (name) {
  22710. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22711. };
  22712. Camera.prototype.getDirection = function (localAxis) {
  22713. var result = BABYLON.Vector3.Zero();
  22714. this.getDirectionToRef(localAxis, result);
  22715. return result;
  22716. };
  22717. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22718. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22719. };
  22720. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22721. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22722. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22723. switch (type) {
  22724. case "ArcRotateCamera":
  22725. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22726. case "DeviceOrientationCamera":
  22727. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22728. case "FollowCamera":
  22729. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22730. case "ArcFollowCamera":
  22731. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22732. case "GamepadCamera":
  22733. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22734. case "TouchCamera":
  22735. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22736. case "VirtualJoysticksCamera":
  22737. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22738. case "WebVRFreeCamera":
  22739. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22740. case "WebVRGamepadCamera":
  22741. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22742. case "VRDeviceOrientationFreeCamera":
  22743. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22744. case "VRDeviceOrientationGamepadCamera":
  22745. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22746. case "AnaglyphArcRotateCamera":
  22747. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22748. case "AnaglyphFreeCamera":
  22749. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22750. case "AnaglyphGamepadCamera":
  22751. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22752. case "AnaglyphUniversalCamera":
  22753. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22754. case "StereoscopicArcRotateCamera":
  22755. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22756. case "StereoscopicFreeCamera":
  22757. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22758. case "StereoscopicGamepadCamera":
  22759. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22760. case "StereoscopicUniversalCamera":
  22761. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22762. case "FreeCamera": // Forcing Universal here
  22763. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22764. default: // Universal Camera is the default value
  22765. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22766. }
  22767. };
  22768. Camera.prototype.computeWorldMatrix = function () {
  22769. return this.getWorldMatrix();
  22770. };
  22771. Camera.Parse = function (parsedCamera, scene) {
  22772. var type = parsedCamera.type;
  22773. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22774. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22775. // Parent
  22776. if (parsedCamera.parentId) {
  22777. camera._waitingParentId = parsedCamera.parentId;
  22778. }
  22779. //If camera has an input manager, let it parse inputs settings
  22780. if (camera.inputs) {
  22781. camera.inputs.parse(parsedCamera);
  22782. camera._setupInputs();
  22783. }
  22784. if (camera.setPosition) { // need to force position
  22785. camera.position.copyFromFloats(0, 0, 0);
  22786. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22787. }
  22788. // Target
  22789. if (parsedCamera.target) {
  22790. if (camera.setTarget) {
  22791. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22792. }
  22793. }
  22794. // Apply 3d rig, when found
  22795. if (parsedCamera.cameraRigMode) {
  22796. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22797. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22798. }
  22799. // Animations
  22800. if (parsedCamera.animations) {
  22801. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22802. var parsedAnimation = parsedCamera.animations[animationIndex];
  22803. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22804. }
  22805. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22806. }
  22807. if (parsedCamera.autoAnimate) {
  22808. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22809. }
  22810. return camera;
  22811. };
  22812. // Statics
  22813. Camera._PERSPECTIVE_CAMERA = 0;
  22814. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22815. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22816. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22817. Camera._RIG_MODE_NONE = 0;
  22818. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22819. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22820. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22821. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22822. Camera._RIG_MODE_VR = 20;
  22823. Camera._RIG_MODE_WEBVR = 21;
  22824. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22825. Camera.UseAlternateWebVRRendering = false;
  22826. __decorate([
  22827. BABYLON.serializeAsVector3()
  22828. ], Camera.prototype, "position", void 0);
  22829. __decorate([
  22830. BABYLON.serializeAsVector3()
  22831. ], Camera.prototype, "upVector", void 0);
  22832. __decorate([
  22833. BABYLON.serialize()
  22834. ], Camera.prototype, "orthoLeft", void 0);
  22835. __decorate([
  22836. BABYLON.serialize()
  22837. ], Camera.prototype, "orthoRight", void 0);
  22838. __decorate([
  22839. BABYLON.serialize()
  22840. ], Camera.prototype, "orthoBottom", void 0);
  22841. __decorate([
  22842. BABYLON.serialize()
  22843. ], Camera.prototype, "orthoTop", void 0);
  22844. __decorate([
  22845. BABYLON.serialize()
  22846. ], Camera.prototype, "fov", void 0);
  22847. __decorate([
  22848. BABYLON.serialize()
  22849. ], Camera.prototype, "minZ", void 0);
  22850. __decorate([
  22851. BABYLON.serialize()
  22852. ], Camera.prototype, "maxZ", void 0);
  22853. __decorate([
  22854. BABYLON.serialize()
  22855. ], Camera.prototype, "inertia", void 0);
  22856. __decorate([
  22857. BABYLON.serialize()
  22858. ], Camera.prototype, "mode", void 0);
  22859. __decorate([
  22860. BABYLON.serialize()
  22861. ], Camera.prototype, "layerMask", void 0);
  22862. __decorate([
  22863. BABYLON.serialize()
  22864. ], Camera.prototype, "fovMode", void 0);
  22865. __decorate([
  22866. BABYLON.serialize()
  22867. ], Camera.prototype, "cameraRigMode", void 0);
  22868. __decorate([
  22869. BABYLON.serialize()
  22870. ], Camera.prototype, "interaxialDistance", void 0);
  22871. __decorate([
  22872. BABYLON.serialize()
  22873. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22874. return Camera;
  22875. }(BABYLON.Node));
  22876. BABYLON.Camera = Camera;
  22877. })(BABYLON || (BABYLON = {}));
  22878. //# sourceMappingURL=babylon.camera.js.map
  22879. var BABYLON;
  22880. (function (BABYLON) {
  22881. var RenderingManager = /** @class */ (function () {
  22882. function RenderingManager(scene) {
  22883. this._renderingGroups = new Array();
  22884. this._autoClearDepthStencil = {};
  22885. this._customOpaqueSortCompareFn = {};
  22886. this._customAlphaTestSortCompareFn = {};
  22887. this._customTransparentSortCompareFn = {};
  22888. this._renderinGroupInfo = null;
  22889. this._scene = scene;
  22890. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22891. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22892. }
  22893. }
  22894. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22895. if (depth === void 0) { depth = true; }
  22896. if (stencil === void 0) { stencil = true; }
  22897. if (this._depthStencilBufferAlreadyCleaned) {
  22898. return;
  22899. }
  22900. this._scene.getEngine().clear(null, false, depth, stencil);
  22901. this._depthStencilBufferAlreadyCleaned = true;
  22902. };
  22903. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22904. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22905. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22906. var info = null;
  22907. if (observable) {
  22908. if (!this._renderinGroupInfo) {
  22909. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22910. }
  22911. info = this._renderinGroupInfo;
  22912. info.scene = this._scene;
  22913. info.camera = this._scene.activeCamera;
  22914. }
  22915. // Dispatch sprites
  22916. if (renderSprites) {
  22917. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22918. var manager = this._scene.spriteManagers[index];
  22919. this.dispatchSprites(manager);
  22920. }
  22921. }
  22922. // Render
  22923. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22924. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22925. var renderingGroup = this._renderingGroups[index];
  22926. if (!renderingGroup && !observable)
  22927. continue;
  22928. var renderingGroupMask = 0;
  22929. // Fire PRECLEAR stage
  22930. if (observable && info) {
  22931. renderingGroupMask = Math.pow(2, index);
  22932. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22933. info.renderingGroupId = index;
  22934. observable.notifyObservers(info, renderingGroupMask);
  22935. }
  22936. // Clear depth/stencil if needed
  22937. if (RenderingManager.AUTOCLEAR) {
  22938. var autoClear = this._autoClearDepthStencil[index];
  22939. if (autoClear && autoClear.autoClear) {
  22940. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22941. }
  22942. }
  22943. if (observable && info) {
  22944. // Fire PREOPAQUE stage
  22945. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22946. observable.notifyObservers(info, renderingGroupMask);
  22947. // Fire PRETRANSPARENT stage
  22948. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22949. observable.notifyObservers(info, renderingGroupMask);
  22950. }
  22951. if (renderingGroup)
  22952. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22953. // Fire POSTTRANSPARENT stage
  22954. if (observable && info) {
  22955. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22956. observable.notifyObservers(info, renderingGroupMask);
  22957. }
  22958. }
  22959. };
  22960. RenderingManager.prototype.reset = function () {
  22961. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22962. var renderingGroup = this._renderingGroups[index];
  22963. if (renderingGroup) {
  22964. renderingGroup.prepare();
  22965. }
  22966. }
  22967. };
  22968. RenderingManager.prototype.dispose = function () {
  22969. this.freeRenderingGroups();
  22970. this._renderingGroups.length = 0;
  22971. };
  22972. /**
  22973. * Clear the info related to rendering groups preventing retention points during dispose.
  22974. */
  22975. RenderingManager.prototype.freeRenderingGroups = function () {
  22976. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22977. var renderingGroup = this._renderingGroups[index];
  22978. if (renderingGroup) {
  22979. renderingGroup.dispose();
  22980. }
  22981. }
  22982. };
  22983. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22984. if (this._renderingGroups[renderingGroupId] === undefined) {
  22985. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22986. }
  22987. };
  22988. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22989. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22990. this._prepareRenderingGroup(renderingGroupId);
  22991. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22992. };
  22993. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22994. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22995. this._prepareRenderingGroup(renderingGroupId);
  22996. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22997. };
  22998. /**
  22999. * @param subMesh The submesh to dispatch
  23000. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23001. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23002. */
  23003. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23004. if (mesh === undefined) {
  23005. mesh = subMesh.getMesh();
  23006. }
  23007. var renderingGroupId = mesh.renderingGroupId || 0;
  23008. this._prepareRenderingGroup(renderingGroupId);
  23009. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23010. };
  23011. /**
  23012. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23013. * This allowed control for front to back rendering or reversly depending of the special needs.
  23014. *
  23015. * @param renderingGroupId The rendering group id corresponding to its index
  23016. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23017. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23018. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23019. */
  23020. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23021. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23022. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23023. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23024. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23025. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23026. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23027. if (this._renderingGroups[renderingGroupId]) {
  23028. var group = this._renderingGroups[renderingGroupId];
  23029. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23030. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23031. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23032. }
  23033. };
  23034. /**
  23035. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23036. *
  23037. * @param renderingGroupId The rendering group id corresponding to its index
  23038. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23039. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23040. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23041. */
  23042. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23043. if (depth === void 0) { depth = true; }
  23044. if (stencil === void 0) { stencil = true; }
  23045. this._autoClearDepthStencil[renderingGroupId] = {
  23046. autoClear: autoClearDepthStencil,
  23047. depth: depth,
  23048. stencil: stencil
  23049. };
  23050. };
  23051. /**
  23052. * The max id used for rendering groups (not included)
  23053. */
  23054. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23055. /**
  23056. * The min id used for rendering groups (included)
  23057. */
  23058. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23059. /**
  23060. * Used to globally prevent autoclearing scenes.
  23061. */
  23062. RenderingManager.AUTOCLEAR = true;
  23063. return RenderingManager;
  23064. }());
  23065. BABYLON.RenderingManager = RenderingManager;
  23066. })(BABYLON || (BABYLON = {}));
  23067. //# sourceMappingURL=babylon.renderingManager.js.map
  23068. var BABYLON;
  23069. (function (BABYLON) {
  23070. var RenderingGroup = /** @class */ (function () {
  23071. /**
  23072. * Creates a new rendering group.
  23073. * @param index The rendering group index
  23074. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23075. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23076. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23077. */
  23078. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23079. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23080. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23081. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23082. this.index = index;
  23083. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23084. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23085. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23086. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23087. this._particleSystems = new BABYLON.SmartArray(256);
  23088. this._spriteManagers = new BABYLON.SmartArray(256);
  23089. this._edgesRenderers = new BABYLON.SmartArray(16);
  23090. this._scene = scene;
  23091. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23092. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23093. this.transparentSortCompareFn = transparentSortCompareFn;
  23094. }
  23095. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23096. /**
  23097. * Set the opaque sort comparison function.
  23098. * If null the sub meshes will be render in the order they were created
  23099. */
  23100. set: function (value) {
  23101. this._opaqueSortCompareFn = value;
  23102. if (value) {
  23103. this._renderOpaque = this.renderOpaqueSorted;
  23104. }
  23105. else {
  23106. this._renderOpaque = RenderingGroup.renderUnsorted;
  23107. }
  23108. },
  23109. enumerable: true,
  23110. configurable: true
  23111. });
  23112. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23113. /**
  23114. * Set the alpha test sort comparison function.
  23115. * If null the sub meshes will be render in the order they were created
  23116. */
  23117. set: function (value) {
  23118. this._alphaTestSortCompareFn = value;
  23119. if (value) {
  23120. this._renderAlphaTest = this.renderAlphaTestSorted;
  23121. }
  23122. else {
  23123. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23124. }
  23125. },
  23126. enumerable: true,
  23127. configurable: true
  23128. });
  23129. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23130. /**
  23131. * Set the transparent sort comparison function.
  23132. * If null the sub meshes will be render in the order they were created
  23133. */
  23134. set: function (value) {
  23135. if (value) {
  23136. this._transparentSortCompareFn = value;
  23137. }
  23138. else {
  23139. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23140. }
  23141. this._renderTransparent = this.renderTransparentSorted;
  23142. },
  23143. enumerable: true,
  23144. configurable: true
  23145. });
  23146. /**
  23147. * Render all the sub meshes contained in the group.
  23148. * @param customRenderFunction Used to override the default render behaviour of the group.
  23149. * @returns true if rendered some submeshes.
  23150. */
  23151. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23152. if (customRenderFunction) {
  23153. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23154. return;
  23155. }
  23156. var engine = this._scene.getEngine();
  23157. // Depth only
  23158. if (this._depthOnlySubMeshes.length !== 0) {
  23159. engine.setColorWrite(false);
  23160. this._renderAlphaTest(this._depthOnlySubMeshes);
  23161. engine.setColorWrite(true);
  23162. }
  23163. // Opaque
  23164. if (this._opaqueSubMeshes.length !== 0) {
  23165. this._renderOpaque(this._opaqueSubMeshes);
  23166. }
  23167. // Alpha test
  23168. if (this._alphaTestSubMeshes.length !== 0) {
  23169. this._renderAlphaTest(this._alphaTestSubMeshes);
  23170. }
  23171. var stencilState = engine.getStencilBuffer();
  23172. engine.setStencilBuffer(false);
  23173. // Sprites
  23174. if (renderSprites) {
  23175. this._renderSprites();
  23176. }
  23177. // Particles
  23178. if (renderParticles) {
  23179. this._renderParticles(activeMeshes);
  23180. }
  23181. if (this.onBeforeTransparentRendering) {
  23182. this.onBeforeTransparentRendering();
  23183. }
  23184. // Transparent
  23185. if (this._transparentSubMeshes.length !== 0) {
  23186. this._renderTransparent(this._transparentSubMeshes);
  23187. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23188. }
  23189. // Set back stencil to false in case it changes before the edge renderer.
  23190. engine.setStencilBuffer(false);
  23191. // Edges
  23192. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23193. this._edgesRenderers.data[edgesRendererIndex].render();
  23194. }
  23195. // Restore Stencil state.
  23196. engine.setStencilBuffer(stencilState);
  23197. };
  23198. /**
  23199. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23200. * @param subMeshes The submeshes to render
  23201. */
  23202. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23203. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23204. };
  23205. /**
  23206. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23207. * @param subMeshes The submeshes to render
  23208. */
  23209. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23210. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23211. };
  23212. /**
  23213. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23214. * @param subMeshes The submeshes to render
  23215. */
  23216. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23217. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23218. };
  23219. /**
  23220. * Renders the submeshes in a specified order.
  23221. * @param subMeshes The submeshes to sort before render
  23222. * @param sortCompareFn The comparison function use to sort
  23223. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23224. * @param transparent Specifies to activate blending if true
  23225. */
  23226. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23227. var subIndex = 0;
  23228. var subMesh;
  23229. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23230. for (; subIndex < subMeshes.length; subIndex++) {
  23231. subMesh = subMeshes.data[subIndex];
  23232. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23233. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23234. }
  23235. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23236. if (sortCompareFn) {
  23237. sortedArray.sort(sortCompareFn);
  23238. }
  23239. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23240. subMesh = sortedArray[subIndex];
  23241. if (transparent) {
  23242. var material = subMesh.getMaterial();
  23243. if (material && material.needDepthPrePass) {
  23244. var engine = material.getScene().getEngine();
  23245. engine.setColorWrite(false);
  23246. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23247. subMesh.render(false);
  23248. engine.setColorWrite(true);
  23249. }
  23250. }
  23251. subMesh.render(transparent);
  23252. }
  23253. };
  23254. /**
  23255. * Renders the submeshes in the order they were dispatched (no sort applied).
  23256. * @param subMeshes The submeshes to render
  23257. */
  23258. RenderingGroup.renderUnsorted = function (subMeshes) {
  23259. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23260. var submesh = subMeshes.data[subIndex];
  23261. submesh.render(false);
  23262. }
  23263. };
  23264. /**
  23265. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23266. * are rendered back to front if in the same alpha index.
  23267. *
  23268. * @param a The first submesh
  23269. * @param b The second submesh
  23270. * @returns The result of the comparison
  23271. */
  23272. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23273. // Alpha index first
  23274. if (a._alphaIndex > b._alphaIndex) {
  23275. return 1;
  23276. }
  23277. if (a._alphaIndex < b._alphaIndex) {
  23278. return -1;
  23279. }
  23280. // Then distance to camera
  23281. return RenderingGroup.backToFrontSortCompare(a, b);
  23282. };
  23283. /**
  23284. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23285. * are rendered back to front.
  23286. *
  23287. * @param a The first submesh
  23288. * @param b The second submesh
  23289. * @returns The result of the comparison
  23290. */
  23291. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23292. // Then distance to camera
  23293. if (a._distanceToCamera < b._distanceToCamera) {
  23294. return 1;
  23295. }
  23296. if (a._distanceToCamera > b._distanceToCamera) {
  23297. return -1;
  23298. }
  23299. return 0;
  23300. };
  23301. /**
  23302. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23303. * are rendered front to back (prevent overdraw).
  23304. *
  23305. * @param a The first submesh
  23306. * @param b The second submesh
  23307. * @returns The result of the comparison
  23308. */
  23309. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23310. // Then distance to camera
  23311. if (a._distanceToCamera < b._distanceToCamera) {
  23312. return -1;
  23313. }
  23314. if (a._distanceToCamera > b._distanceToCamera) {
  23315. return 1;
  23316. }
  23317. return 0;
  23318. };
  23319. /**
  23320. * Resets the different lists of submeshes to prepare a new frame.
  23321. */
  23322. RenderingGroup.prototype.prepare = function () {
  23323. this._opaqueSubMeshes.reset();
  23324. this._transparentSubMeshes.reset();
  23325. this._alphaTestSubMeshes.reset();
  23326. this._depthOnlySubMeshes.reset();
  23327. this._particleSystems.reset();
  23328. this._spriteManagers.reset();
  23329. this._edgesRenderers.reset();
  23330. };
  23331. RenderingGroup.prototype.dispose = function () {
  23332. this._opaqueSubMeshes.dispose();
  23333. this._transparentSubMeshes.dispose();
  23334. this._alphaTestSubMeshes.dispose();
  23335. this._depthOnlySubMeshes.dispose();
  23336. this._particleSystems.dispose();
  23337. this._spriteManagers.dispose();
  23338. this._edgesRenderers.dispose();
  23339. };
  23340. /**
  23341. * Inserts the submesh in its correct queue depending on its material.
  23342. * @param subMesh The submesh to dispatch
  23343. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23344. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23345. */
  23346. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23347. // Get mesh and materials if not provided
  23348. if (mesh === undefined) {
  23349. mesh = subMesh.getMesh();
  23350. }
  23351. if (material === undefined) {
  23352. material = subMesh.getMaterial();
  23353. }
  23354. if (material === null || material === undefined) {
  23355. return;
  23356. }
  23357. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23358. this._transparentSubMeshes.push(subMesh);
  23359. }
  23360. else if (material.needAlphaTesting()) { // Alpha test
  23361. if (material.needDepthPrePass) {
  23362. this._depthOnlySubMeshes.push(subMesh);
  23363. }
  23364. this._alphaTestSubMeshes.push(subMesh);
  23365. }
  23366. else {
  23367. if (material.needDepthPrePass) {
  23368. this._depthOnlySubMeshes.push(subMesh);
  23369. }
  23370. this._opaqueSubMeshes.push(subMesh); // Opaque
  23371. }
  23372. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23373. this._edgesRenderers.push(mesh._edgesRenderer);
  23374. }
  23375. };
  23376. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23377. this._spriteManagers.push(spriteManager);
  23378. };
  23379. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23380. this._particleSystems.push(particleSystem);
  23381. };
  23382. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23383. if (this._particleSystems.length === 0) {
  23384. return;
  23385. }
  23386. // Particles
  23387. var activeCamera = this._scene.activeCamera;
  23388. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23389. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23390. var particleSystem = this._particleSystems.data[particleIndex];
  23391. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23392. continue;
  23393. }
  23394. var emitter = particleSystem.emitter;
  23395. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23396. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23397. }
  23398. }
  23399. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23400. };
  23401. RenderingGroup.prototype._renderSprites = function () {
  23402. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23403. return;
  23404. }
  23405. // Sprites
  23406. var activeCamera = this._scene.activeCamera;
  23407. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23408. for (var id = 0; id < this._spriteManagers.length; id++) {
  23409. var spriteManager = this._spriteManagers.data[id];
  23410. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23411. spriteManager.render();
  23412. }
  23413. }
  23414. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23415. };
  23416. return RenderingGroup;
  23417. }());
  23418. BABYLON.RenderingGroup = RenderingGroup;
  23419. })(BABYLON || (BABYLON = {}));
  23420. //# sourceMappingURL=babylon.renderingGroup.js.map
  23421. var BABYLON;
  23422. (function (BABYLON) {
  23423. /** @hidden */
  23424. var ClickInfo = /** @class */ (function () {
  23425. function ClickInfo() {
  23426. this._singleClick = false;
  23427. this._doubleClick = false;
  23428. this._hasSwiped = false;
  23429. this._ignore = false;
  23430. }
  23431. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23432. get: function () {
  23433. return this._singleClick;
  23434. },
  23435. set: function (b) {
  23436. this._singleClick = b;
  23437. },
  23438. enumerable: true,
  23439. configurable: true
  23440. });
  23441. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23442. get: function () {
  23443. return this._doubleClick;
  23444. },
  23445. set: function (b) {
  23446. this._doubleClick = b;
  23447. },
  23448. enumerable: true,
  23449. configurable: true
  23450. });
  23451. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23452. get: function () {
  23453. return this._hasSwiped;
  23454. },
  23455. set: function (b) {
  23456. this._hasSwiped = b;
  23457. },
  23458. enumerable: true,
  23459. configurable: true
  23460. });
  23461. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23462. get: function () {
  23463. return this._ignore;
  23464. },
  23465. set: function (b) {
  23466. this._ignore = b;
  23467. },
  23468. enumerable: true,
  23469. configurable: true
  23470. });
  23471. return ClickInfo;
  23472. }());
  23473. /**
  23474. * This class is used by the onRenderingGroupObservable
  23475. */
  23476. var RenderingGroupInfo = /** @class */ (function () {
  23477. function RenderingGroupInfo() {
  23478. }
  23479. /**
  23480. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23481. * This stage will be fired no matter what
  23482. */
  23483. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23484. /**
  23485. * Called before opaque object are rendered.
  23486. * This stage will be fired only if there's 3D Opaque content to render
  23487. */
  23488. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23489. /**
  23490. * Called after the opaque objects are rendered and before the transparent ones
  23491. * This stage will be fired only if there's 3D transparent content to render
  23492. */
  23493. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23494. /**
  23495. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23496. * This stage will be fired no matter what
  23497. */
  23498. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23499. return RenderingGroupInfo;
  23500. }());
  23501. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23502. /**
  23503. * Represents a scene to be rendered by the engine.
  23504. * @see http://doc.babylonjs.com/features/scene
  23505. */
  23506. var Scene = /** @class */ (function () {
  23507. /**
  23508. * Creates a new Scene
  23509. * @param engine defines the engine to use to render this scene
  23510. */
  23511. function Scene(engine) {
  23512. // Members
  23513. /**
  23514. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23515. */
  23516. this.autoClear = true;
  23517. /**
  23518. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23519. */
  23520. this.autoClearDepthAndStencil = true;
  23521. /**
  23522. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23523. */
  23524. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23525. /**
  23526. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23527. */
  23528. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23529. this._forceWireframe = false;
  23530. this._forcePointsCloud = false;
  23531. /**
  23532. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23533. */
  23534. this.forceShowBoundingBoxes = false;
  23535. /**
  23536. * Gets or sets a boolean indicating if animations are enabled
  23537. */
  23538. this.animationsEnabled = true;
  23539. this._animationPropertiesOverride = null;
  23540. /**
  23541. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23542. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23543. */
  23544. this.useConstantAnimationDeltaTime = false;
  23545. /**
  23546. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23547. * Please note that it requires to run a ray cast through the scene on every frame
  23548. */
  23549. this.constantlyUpdateMeshUnderPointer = false;
  23550. /**
  23551. * Defines the HTML cursor to use when hovering over interactive elements
  23552. */
  23553. this.hoverCursor = "pointer";
  23554. /**
  23555. * Defines the HTML default cursor to use (empty by default)
  23556. */
  23557. this.defaultCursor = "";
  23558. /**
  23559. * This is used to call preventDefault() on pointer down
  23560. * in order to block unwanted artifacts like system double clicks
  23561. */
  23562. this.preventDefaultOnPointerDown = true;
  23563. // Metadata
  23564. /**
  23565. * Gets or sets user defined metadata
  23566. */
  23567. this.metadata = null;
  23568. /**
  23569. * Use this array to add regular expressions used to disable offline support for specific urls
  23570. */
  23571. this.disableOfflineSupportExceptionRules = new Array();
  23572. /**
  23573. * An event triggered when the scene is disposed.
  23574. */
  23575. this.onDisposeObservable = new BABYLON.Observable();
  23576. this._onDisposeObserver = null;
  23577. /**
  23578. * An event triggered before rendering the scene (right after animations and physics)
  23579. */
  23580. this.onBeforeRenderObservable = new BABYLON.Observable();
  23581. this._onBeforeRenderObserver = null;
  23582. /**
  23583. * An event triggered after rendering the scene
  23584. */
  23585. this.onAfterRenderObservable = new BABYLON.Observable();
  23586. this._onAfterRenderObserver = null;
  23587. /**
  23588. * An event triggered before animating the scene
  23589. */
  23590. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23591. /**
  23592. * An event triggered after animations processing
  23593. */
  23594. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23595. /**
  23596. * An event triggered before draw calls are ready to be sent
  23597. */
  23598. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23599. /**
  23600. * An event triggered after draw calls have been sent
  23601. */
  23602. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23603. /**
  23604. * An event triggered when physic simulation is about to be run
  23605. */
  23606. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23607. /**
  23608. * An event triggered when physic simulation has been done
  23609. */
  23610. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23611. /**
  23612. * An event triggered when the scene is ready
  23613. */
  23614. this.onReadyObservable = new BABYLON.Observable();
  23615. /**
  23616. * An event triggered before rendering a camera
  23617. */
  23618. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23619. this._onBeforeCameraRenderObserver = null;
  23620. /**
  23621. * An event triggered after rendering a camera
  23622. */
  23623. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23624. this._onAfterCameraRenderObserver = null;
  23625. /**
  23626. * An event triggered when active meshes evaluation is about to start
  23627. */
  23628. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered when active meshes evaluation is done
  23631. */
  23632. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23633. /**
  23634. * An event triggered when particles rendering is about to start
  23635. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23636. */
  23637. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23638. /**
  23639. * An event triggered when particles rendering is done
  23640. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23641. */
  23642. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23643. /**
  23644. * An event triggered when sprites rendering is about to start
  23645. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23646. */
  23647. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered when sprites rendering is done
  23650. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23651. */
  23652. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23655. */
  23656. this.onDataLoadedObservable = new BABYLON.Observable();
  23657. /**
  23658. * An event triggered when a camera is created
  23659. */
  23660. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23661. /**
  23662. * An event triggered when a camera is removed
  23663. */
  23664. this.onCameraRemovedObservable = new BABYLON.Observable();
  23665. /**
  23666. * An event triggered when a light is created
  23667. */
  23668. this.onNewLightAddedObservable = new BABYLON.Observable();
  23669. /**
  23670. * An event triggered when a light is removed
  23671. */
  23672. this.onLightRemovedObservable = new BABYLON.Observable();
  23673. /**
  23674. * An event triggered when a geometry is created
  23675. */
  23676. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23677. /**
  23678. * An event triggered when a geometry is removed
  23679. */
  23680. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23681. /**
  23682. * An event triggered when a transform node is created
  23683. */
  23684. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23685. /**
  23686. * An event triggered when a transform node is removed
  23687. */
  23688. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23689. /**
  23690. * An event triggered when a mesh is created
  23691. */
  23692. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23693. /**
  23694. * An event triggered when a mesh is removed
  23695. */
  23696. this.onMeshRemovedObservable = new BABYLON.Observable();
  23697. /**
  23698. * An event triggered when render targets are about to be rendered
  23699. * Can happen multiple times per frame.
  23700. */
  23701. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered when render targets were rendered.
  23704. * Can happen multiple times per frame.
  23705. */
  23706. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered before calculating deterministic simulation step
  23709. */
  23710. this.onBeforeStepObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered after calculating deterministic simulation step
  23713. */
  23714. this.onAfterStepObservable = new BABYLON.Observable();
  23715. /**
  23716. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23717. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23718. * 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)
  23719. */
  23720. this.onRenderingGroupObservable = new BABYLON.Observable();
  23721. // Animations
  23722. /**
  23723. * Gets a list of Animations associated with the scene
  23724. */
  23725. this.animations = [];
  23726. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23727. /**
  23728. * 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).
  23729. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23730. */
  23731. this.onPrePointerObservable = new BABYLON.Observable();
  23732. /**
  23733. * Observable event triggered each time an input event is received from the rendering canvas
  23734. */
  23735. this.onPointerObservable = new BABYLON.Observable();
  23736. this._meshPickProceed = false;
  23737. this._currentPickResult = null;
  23738. this._previousPickResult = null;
  23739. this._totalPointersPressed = 0;
  23740. this._doubleClickOccured = false;
  23741. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23742. this.cameraToUseForPointers = null;
  23743. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23744. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23745. this._startingPointerTime = 0;
  23746. this._previousStartingPointerTime = 0;
  23747. // Deterministic lockstep
  23748. this._timeAccumulator = 0;
  23749. this._currentStepId = 0;
  23750. this._currentInternalStep = 0;
  23751. // Keyboard
  23752. /**
  23753. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23754. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23755. */
  23756. this.onPreKeyboardObservable = new BABYLON.Observable();
  23757. /**
  23758. * Observable event triggered each time an keyboard event is received from the hosting window
  23759. */
  23760. this.onKeyboardObservable = new BABYLON.Observable();
  23761. // Coordinates system
  23762. this._useRightHandedSystem = false;
  23763. // Fog
  23764. this._fogEnabled = true;
  23765. this._fogMode = Scene.FOGMODE_NONE;
  23766. /**
  23767. * Gets or sets the fog color to use
  23768. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23769. */
  23770. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23771. /**
  23772. * Gets or sets the fog density to use
  23773. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23774. */
  23775. this.fogDensity = 0.1;
  23776. /**
  23777. * Gets or sets the fog start distance to use
  23778. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23779. */
  23780. this.fogStart = 0;
  23781. /**
  23782. * Gets or sets the fog end distance to use
  23783. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23784. */
  23785. this.fogEnd = 1000.0;
  23786. // Lights
  23787. this._shadowsEnabled = true;
  23788. this._lightsEnabled = true;
  23789. /**
  23790. * All of the lights added to this scene
  23791. * @see http://doc.babylonjs.com/babylon101/lights
  23792. */
  23793. this.lights = new Array();
  23794. // Cameras
  23795. /** All of the cameras added to this scene.
  23796. * @see http://doc.babylonjs.com/babylon101/cameras
  23797. */
  23798. this.cameras = new Array();
  23799. /** All of the active cameras added to this scene. */
  23800. this.activeCameras = new Array();
  23801. // Meshes
  23802. /**
  23803. * All of the tranform nodes added to this scene
  23804. * @see http://doc.babylonjs.com/how_to/transformnode
  23805. */
  23806. this.transformNodes = new Array();
  23807. /**
  23808. * All of the (abstract) meshes added to this scene
  23809. */
  23810. this.meshes = new Array();
  23811. /**
  23812. * All of the animation groups added to this scene
  23813. * @see http://doc.babylonjs.com/how_to/group
  23814. */
  23815. this.animationGroups = new Array();
  23816. // Geometries
  23817. this._geometries = new Array();
  23818. /**
  23819. * All of the materials added to this scene
  23820. * @see http://doc.babylonjs.com/babylon101/materials
  23821. */
  23822. this.materials = new Array();
  23823. /**
  23824. * All of the multi-materials added to this scene
  23825. * @see http://doc.babylonjs.com/how_to/multi_materials
  23826. */
  23827. this.multiMaterials = new Array();
  23828. // Textures
  23829. this._texturesEnabled = true;
  23830. /**
  23831. * All of the textures added to this scene
  23832. */
  23833. this.textures = new Array();
  23834. // Particles
  23835. /**
  23836. * Gets or sets a boolean indicating if particles are enabled on this scene
  23837. */
  23838. this.particlesEnabled = true;
  23839. /**
  23840. * All of the particle systems added to this scene
  23841. * @see http://doc.babylonjs.com/babylon101/particles
  23842. */
  23843. this.particleSystems = new Array();
  23844. // Sprites
  23845. /**
  23846. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23847. */
  23848. this.spritesEnabled = true;
  23849. /**
  23850. * All of the sprite managers added to this scene
  23851. * @see http://doc.babylonjs.com/babylon101/sprites
  23852. */
  23853. this.spriteManagers = new Array();
  23854. /**
  23855. * The list of layers (background and foreground) of the scene
  23856. */
  23857. this.layers = new Array();
  23858. /**
  23859. * The list of effect layers (highlights/glow) added to the scene
  23860. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23861. * @see http://doc.babylonjs.com/how_to/glow_layer
  23862. */
  23863. this.effectLayers = new Array();
  23864. // Skeletons
  23865. this._skeletonsEnabled = true;
  23866. /**
  23867. * The list of skeletons added to the scene
  23868. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23869. */
  23870. this.skeletons = new Array();
  23871. // Morph targets
  23872. /**
  23873. * The list of morph target managers added to the scene
  23874. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23875. */
  23876. this.morphTargetManagers = new Array();
  23877. // Lens flares
  23878. /**
  23879. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23880. */
  23881. this.lensFlaresEnabled = true;
  23882. /**
  23883. * The list of lens flare system added to the scene
  23884. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23885. */
  23886. this.lensFlareSystems = new Array();
  23887. // Collisions
  23888. /**
  23889. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23890. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23891. */
  23892. this.collisionsEnabled = true;
  23893. /**
  23894. * Defines the gravity applied to this scene (used only for collisions)
  23895. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23896. */
  23897. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23898. // Postprocesses
  23899. /**
  23900. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23901. */
  23902. this.postProcessesEnabled = true;
  23903. /**
  23904. * The list of postprocesses added to the scene
  23905. */
  23906. this.postProcesses = new Array();
  23907. // Customs render targets
  23908. /**
  23909. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23910. */
  23911. this.renderTargetsEnabled = true;
  23912. /**
  23913. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23914. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23915. */
  23916. this.dumpNextRenderTargets = false;
  23917. /**
  23918. * The list of user defined render targets added to the scene
  23919. */
  23920. this.customRenderTargets = new Array();
  23921. /**
  23922. * Gets the list of meshes imported to the scene through SceneLoader
  23923. */
  23924. this.importedMeshesFiles = new Array();
  23925. // Probes
  23926. /**
  23927. * Gets or sets a boolean indicating if probes are enabled on this scene
  23928. */
  23929. this.probesEnabled = true;
  23930. /**
  23931. * The list of reflection probes added to the scene
  23932. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23933. */
  23934. this.reflectionProbes = new Array();
  23935. /** @hidden */
  23936. this._actionManagers = new Array();
  23937. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23938. // Procedural textures
  23939. /**
  23940. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23941. */
  23942. this.proceduralTexturesEnabled = true;
  23943. /**
  23944. * The list of procedural textures added to the scene
  23945. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23946. */
  23947. this.proceduralTextures = new Array();
  23948. /**
  23949. * The list of sound tracks added to the scene
  23950. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23951. */
  23952. this.soundTracks = new Array();
  23953. this._audioEnabled = true;
  23954. this._headphone = false;
  23955. // Performance counters
  23956. this._totalVertices = new BABYLON.PerfCounter();
  23957. /** @hidden */
  23958. this._activeIndices = new BABYLON.PerfCounter();
  23959. /** @hidden */
  23960. this._activeParticles = new BABYLON.PerfCounter();
  23961. /** @hidden */
  23962. this._activeBones = new BABYLON.PerfCounter();
  23963. this._animationTime = 0;
  23964. /**
  23965. * Gets or sets a general scale for animation speed
  23966. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23967. */
  23968. this.animationTimeScale = 1;
  23969. this._renderId = 0;
  23970. this._executeWhenReadyTimeoutId = -1;
  23971. this._intermediateRendering = false;
  23972. this._viewUpdateFlag = -1;
  23973. this._projectionUpdateFlag = -1;
  23974. this._alternateViewUpdateFlag = -1;
  23975. this._alternateProjectionUpdateFlag = -1;
  23976. /** @hidden */
  23977. this._toBeDisposed = new BABYLON.SmartArray(256);
  23978. this._activeRequests = new Array();
  23979. this._pendingData = new Array();
  23980. this._isDisposed = false;
  23981. /**
  23982. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23983. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23984. */
  23985. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23986. this._activeMeshes = new BABYLON.SmartArray(256);
  23987. this._processedMaterials = new BABYLON.SmartArray(256);
  23988. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23989. /** @hidden */
  23990. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23991. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23992. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23993. /** @hidden */
  23994. this._activeAnimatables = new Array();
  23995. this._transformMatrix = BABYLON.Matrix.Zero();
  23996. this._useAlternateCameraConfiguration = false;
  23997. this._alternateRendering = false;
  23998. /**
  23999. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24000. * This is useful if there are more lights that the maximum simulteanous authorized
  24001. */
  24002. this.requireLightSorting = false;
  24003. this._depthRenderer = {};
  24004. this._activeMeshesFrozen = false;
  24005. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24006. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24007. this._engine.scenes.push(this);
  24008. this._uid = null;
  24009. this._renderingManager = new BABYLON.RenderingManager(this);
  24010. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24011. if (BABYLON.OutlineRenderer) {
  24012. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24013. }
  24014. if (BABYLON.Tools.IsWindowObjectExist()) {
  24015. this.attachControl();
  24016. }
  24017. //simplification queue
  24018. if (BABYLON.SimplificationQueue) {
  24019. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24020. }
  24021. //collision coordinator initialization. For now legacy per default.
  24022. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24023. // Uniform Buffer
  24024. this._createUbo();
  24025. // Default Image processing definition.
  24026. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24027. }
  24028. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24029. /** The fog is deactivated */
  24030. get: function () {
  24031. return Scene._FOGMODE_NONE;
  24032. },
  24033. enumerable: true,
  24034. configurable: true
  24035. });
  24036. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24037. /** The fog density is following an exponential function */
  24038. get: function () {
  24039. return Scene._FOGMODE_EXP;
  24040. },
  24041. enumerable: true,
  24042. configurable: true
  24043. });
  24044. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24045. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24046. get: function () {
  24047. return Scene._FOGMODE_EXP2;
  24048. },
  24049. enumerable: true,
  24050. configurable: true
  24051. });
  24052. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24053. /** The fog density is following a linear function. */
  24054. get: function () {
  24055. return Scene._FOGMODE_LINEAR;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24061. /**
  24062. * Texture used in all pbr material as the reflection texture.
  24063. * As in the majority of the scene they are the same (exception for multi room and so on),
  24064. * this is easier to reference from here than from all the materials.
  24065. */
  24066. get: function () {
  24067. return this._environmentTexture;
  24068. },
  24069. /**
  24070. * Texture used in all pbr material as the reflection texture.
  24071. * As in the majority of the scene they are the same (exception for multi room and so on),
  24072. * this is easier to set here than in all the materials.
  24073. */
  24074. set: function (value) {
  24075. if (this._environmentTexture === value) {
  24076. return;
  24077. }
  24078. this._environmentTexture = value;
  24079. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24080. },
  24081. enumerable: true,
  24082. configurable: true
  24083. });
  24084. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24085. /**
  24086. * Default image processing configuration used either in the rendering
  24087. * Forward main pass or through the imageProcessingPostProcess if present.
  24088. * As in the majority of the scene they are the same (exception for multi camera),
  24089. * this is easier to reference from here than from all the materials and post process.
  24090. *
  24091. * No setter as we it is a shared configuration, you can set the values instead.
  24092. */
  24093. get: function () {
  24094. return this._imageProcessingConfiguration;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24100. get: function () {
  24101. return this._forceWireframe;
  24102. },
  24103. /**
  24104. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24105. */
  24106. set: function (value) {
  24107. if (this._forceWireframe === value) {
  24108. return;
  24109. }
  24110. this._forceWireframe = value;
  24111. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24112. },
  24113. enumerable: true,
  24114. configurable: true
  24115. });
  24116. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24117. get: function () {
  24118. return this._forcePointsCloud;
  24119. },
  24120. /**
  24121. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24122. */
  24123. set: function (value) {
  24124. if (this._forcePointsCloud === value) {
  24125. return;
  24126. }
  24127. this._forcePointsCloud = value;
  24128. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24129. },
  24130. enumerable: true,
  24131. configurable: true
  24132. });
  24133. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24134. /**
  24135. * Gets or sets the animation properties override
  24136. */
  24137. get: function () {
  24138. return this._animationPropertiesOverride;
  24139. },
  24140. set: function (value) {
  24141. this._animationPropertiesOverride = value;
  24142. },
  24143. enumerable: true,
  24144. configurable: true
  24145. });
  24146. Object.defineProperty(Scene.prototype, "onDispose", {
  24147. /** Sets a function to be executed when this scene is disposed. */
  24148. set: function (callback) {
  24149. if (this._onDisposeObserver) {
  24150. this.onDisposeObservable.remove(this._onDisposeObserver);
  24151. }
  24152. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24153. },
  24154. enumerable: true,
  24155. configurable: true
  24156. });
  24157. Object.defineProperty(Scene.prototype, "beforeRender", {
  24158. /** Sets a function to be executed before rendering this scene */
  24159. set: function (callback) {
  24160. if (this._onBeforeRenderObserver) {
  24161. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24162. }
  24163. if (callback) {
  24164. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24165. }
  24166. },
  24167. enumerable: true,
  24168. configurable: true
  24169. });
  24170. Object.defineProperty(Scene.prototype, "afterRender", {
  24171. /** Sets a function to be executed after rendering this scene */
  24172. set: function (callback) {
  24173. if (this._onAfterRenderObserver) {
  24174. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24175. }
  24176. if (callback) {
  24177. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24178. }
  24179. },
  24180. enumerable: true,
  24181. configurable: true
  24182. });
  24183. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24184. /** Sets a function to be executed before rendering a camera*/
  24185. set: function (callback) {
  24186. if (this._onBeforeCameraRenderObserver) {
  24187. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24188. }
  24189. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24195. /** Sets a function to be executed after rendering a camera*/
  24196. set: function (callback) {
  24197. if (this._onAfterCameraRenderObserver) {
  24198. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24199. }
  24200. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24201. },
  24202. enumerable: true,
  24203. configurable: true
  24204. });
  24205. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24206. /**
  24207. * Gets the gamepad manager associated with the scene
  24208. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24209. */
  24210. get: function () {
  24211. if (!this._gamepadManager) {
  24212. this._gamepadManager = new BABYLON.GamepadManager(this);
  24213. }
  24214. return this._gamepadManager;
  24215. },
  24216. enumerable: true,
  24217. configurable: true
  24218. });
  24219. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24220. /**
  24221. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24222. */
  24223. get: function () {
  24224. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24225. },
  24226. enumerable: true,
  24227. configurable: true
  24228. });
  24229. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24230. get: function () {
  24231. return this._useRightHandedSystem;
  24232. },
  24233. /**
  24234. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24235. */
  24236. set: function (value) {
  24237. if (this._useRightHandedSystem === value) {
  24238. return;
  24239. }
  24240. this._useRightHandedSystem = value;
  24241. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24242. },
  24243. enumerable: true,
  24244. configurable: true
  24245. });
  24246. /**
  24247. * Sets the step Id used by deterministic lock step
  24248. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24249. * @param newStepId defines the step Id
  24250. */
  24251. Scene.prototype.setStepId = function (newStepId) {
  24252. this._currentStepId = newStepId;
  24253. };
  24254. ;
  24255. /**
  24256. * Gets the step Id used by deterministic lock step
  24257. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24258. * @returns the step Id
  24259. */
  24260. Scene.prototype.getStepId = function () {
  24261. return this._currentStepId;
  24262. };
  24263. ;
  24264. /**
  24265. * Gets the internal step used by deterministic lock step
  24266. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24267. * @returns the internal step
  24268. */
  24269. Scene.prototype.getInternalStep = function () {
  24270. return this._currentInternalStep;
  24271. };
  24272. ;
  24273. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24274. get: function () {
  24275. return this._fogEnabled;
  24276. },
  24277. /**
  24278. * Gets or sets a boolean indicating if fog is enabled on this scene
  24279. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24280. */
  24281. set: function (value) {
  24282. if (this._fogEnabled === value) {
  24283. return;
  24284. }
  24285. this._fogEnabled = value;
  24286. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24287. },
  24288. enumerable: true,
  24289. configurable: true
  24290. });
  24291. Object.defineProperty(Scene.prototype, "fogMode", {
  24292. get: function () {
  24293. return this._fogMode;
  24294. },
  24295. /**
  24296. * Gets or sets the fog mode to use
  24297. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24298. */
  24299. set: function (value) {
  24300. if (this._fogMode === value) {
  24301. return;
  24302. }
  24303. this._fogMode = value;
  24304. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24305. },
  24306. enumerable: true,
  24307. configurable: true
  24308. });
  24309. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24310. get: function () {
  24311. return this._shadowsEnabled;
  24312. },
  24313. /**
  24314. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24315. */
  24316. set: function (value) {
  24317. if (this._shadowsEnabled === value) {
  24318. return;
  24319. }
  24320. this._shadowsEnabled = value;
  24321. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24322. },
  24323. enumerable: true,
  24324. configurable: true
  24325. });
  24326. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24327. get: function () {
  24328. return this._lightsEnabled;
  24329. },
  24330. /**
  24331. * Gets or sets a boolean indicating if lights are enabled on this scene
  24332. */
  24333. set: function (value) {
  24334. if (this._lightsEnabled === value) {
  24335. return;
  24336. }
  24337. this._lightsEnabled = value;
  24338. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24344. /** The default material used on meshes when no material is affected */
  24345. get: function () {
  24346. if (!this._defaultMaterial) {
  24347. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24348. }
  24349. return this._defaultMaterial;
  24350. },
  24351. /** The default material used on meshes when no material is affected */
  24352. set: function (value) {
  24353. this._defaultMaterial = value;
  24354. },
  24355. enumerable: true,
  24356. configurable: true
  24357. });
  24358. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24359. get: function () {
  24360. return this._texturesEnabled;
  24361. },
  24362. /**
  24363. * Gets or sets a boolean indicating if textures are enabled on this scene
  24364. */
  24365. set: function (value) {
  24366. if (this._texturesEnabled === value) {
  24367. return;
  24368. }
  24369. this._texturesEnabled = value;
  24370. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24371. },
  24372. enumerable: true,
  24373. configurable: true
  24374. });
  24375. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24376. get: function () {
  24377. return this._skeletonsEnabled;
  24378. },
  24379. /**
  24380. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24381. */
  24382. set: function (value) {
  24383. if (this._skeletonsEnabled === value) {
  24384. return;
  24385. }
  24386. this._skeletonsEnabled = value;
  24387. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24388. },
  24389. enumerable: true,
  24390. configurable: true
  24391. });
  24392. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24393. /**
  24394. * Gets the postprocess render pipeline manager
  24395. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24396. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24397. */
  24398. get: function () {
  24399. if (!this._postProcessRenderPipelineManager) {
  24400. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24401. }
  24402. return this._postProcessRenderPipelineManager;
  24403. },
  24404. enumerable: true,
  24405. configurable: true
  24406. });
  24407. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24408. /**
  24409. * Gets the main soundtrack associated with the scene
  24410. */
  24411. get: function () {
  24412. if (!this._mainSoundTrack) {
  24413. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24414. }
  24415. return this._mainSoundTrack;
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24421. /** @hidden */
  24422. get: function () {
  24423. return this._alternateRendering;
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24429. /**
  24430. * Gets the list of frustum planes (built from the active camera)
  24431. */
  24432. get: function () {
  24433. return this._frustumPlanes;
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24439. /**
  24440. * Gets the current geometry buffer associated to the scene.
  24441. */
  24442. get: function () {
  24443. return this._geometryBufferRenderer;
  24444. },
  24445. /**
  24446. * Sets the current geometry buffer for the scene.
  24447. */
  24448. set: function (geometryBufferRenderer) {
  24449. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24450. this._geometryBufferRenderer = geometryBufferRenderer;
  24451. }
  24452. },
  24453. enumerable: true,
  24454. configurable: true
  24455. });
  24456. Object.defineProperty(Scene.prototype, "debugLayer", {
  24457. /**
  24458. * Gets the debug layer associated with the scene
  24459. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24460. */
  24461. get: function () {
  24462. if (!this._debugLayer) {
  24463. this._debugLayer = new BABYLON.DebugLayer(this);
  24464. }
  24465. return this._debugLayer;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24471. /**
  24472. * Gets a boolean indicating if collisions are processed on a web worker
  24473. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24474. */
  24475. get: function () {
  24476. return this._workerCollisions;
  24477. },
  24478. set: function (enabled) {
  24479. if (!BABYLON.CollisionCoordinatorLegacy) {
  24480. return;
  24481. }
  24482. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24483. this._workerCollisions = enabled;
  24484. if (this.collisionCoordinator) {
  24485. this.collisionCoordinator.destroy();
  24486. }
  24487. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24488. this.collisionCoordinator.init(this);
  24489. },
  24490. enumerable: true,
  24491. configurable: true
  24492. });
  24493. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24494. /**
  24495. * Gets the octree used to boost mesh selection (picking)
  24496. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24497. */
  24498. get: function () {
  24499. return this._selectionOctree;
  24500. },
  24501. enumerable: true,
  24502. configurable: true
  24503. });
  24504. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24505. /**
  24506. * Gets the mesh that is currently under the pointer
  24507. */
  24508. get: function () {
  24509. return this._pointerOverMesh;
  24510. },
  24511. enumerable: true,
  24512. configurable: true
  24513. });
  24514. Object.defineProperty(Scene.prototype, "pointerX", {
  24515. /**
  24516. * Gets the current on-screen X position of the pointer
  24517. */
  24518. get: function () {
  24519. return this._pointerX;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(Scene.prototype, "pointerY", {
  24525. /**
  24526. * Gets the current on-screen Y position of the pointer
  24527. */
  24528. get: function () {
  24529. return this._pointerY;
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. /**
  24535. * Gets the cached material (ie. the latest rendered one)
  24536. * @returns the cached material
  24537. */
  24538. Scene.prototype.getCachedMaterial = function () {
  24539. return this._cachedMaterial;
  24540. };
  24541. /**
  24542. * Gets the cached effect (ie. the latest rendered one)
  24543. * @returns the cached effect
  24544. */
  24545. Scene.prototype.getCachedEffect = function () {
  24546. return this._cachedEffect;
  24547. };
  24548. /**
  24549. * Gets the cached visibility state (ie. the latest rendered one)
  24550. * @returns the cached visibility state
  24551. */
  24552. Scene.prototype.getCachedVisibility = function () {
  24553. return this._cachedVisibility;
  24554. };
  24555. /**
  24556. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24557. * @param material defines the current material
  24558. * @param effect defines the current effect
  24559. * @param visibility defines the current visibility state
  24560. * @returns true if one parameter is not cached
  24561. */
  24562. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24563. if (visibility === void 0) { visibility = 1; }
  24564. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24565. };
  24566. /**
  24567. * Gets the bounding box renderer associated with the scene
  24568. * @returns a BoundingBoxRenderer
  24569. */
  24570. Scene.prototype.getBoundingBoxRenderer = function () {
  24571. if (!this._boundingBoxRenderer) {
  24572. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24573. }
  24574. return this._boundingBoxRenderer;
  24575. };
  24576. /**
  24577. * Gets the outline renderer associated with the scene
  24578. * @returns a OutlineRenderer
  24579. */
  24580. Scene.prototype.getOutlineRenderer = function () {
  24581. return this._outlineRenderer;
  24582. };
  24583. /**
  24584. * Gets the engine associated with the scene
  24585. * @returns an Engine
  24586. */
  24587. Scene.prototype.getEngine = function () {
  24588. return this._engine;
  24589. };
  24590. /**
  24591. * Gets the total number of vertices rendered per frame
  24592. * @returns the total number of vertices rendered per frame
  24593. */
  24594. Scene.prototype.getTotalVertices = function () {
  24595. return this._totalVertices.current;
  24596. };
  24597. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24598. /**
  24599. * Gets the performance counter for total vertices
  24600. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24601. */
  24602. get: function () {
  24603. return this._totalVertices;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. /**
  24609. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24610. * @returns the total number of active indices rendered per frame
  24611. */
  24612. Scene.prototype.getActiveIndices = function () {
  24613. return this._activeIndices.current;
  24614. };
  24615. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24616. /**
  24617. * Gets the performance counter for active indices
  24618. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24619. */
  24620. get: function () {
  24621. return this._activeIndices;
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. /**
  24627. * Gets the total number of active particles rendered per frame
  24628. * @returns the total number of active particles rendered per frame
  24629. */
  24630. Scene.prototype.getActiveParticles = function () {
  24631. return this._activeParticles.current;
  24632. };
  24633. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24634. /**
  24635. * Gets the performance counter for active particles
  24636. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24637. */
  24638. get: function () {
  24639. return this._activeParticles;
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. /**
  24645. * Gets the total number of active bones rendered per frame
  24646. * @returns the total number of active bones rendered per frame
  24647. */
  24648. Scene.prototype.getActiveBones = function () {
  24649. return this._activeBones.current;
  24650. };
  24651. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24652. /**
  24653. * Gets the performance counter for active bones
  24654. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24655. */
  24656. get: function () {
  24657. return this._activeBones;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. /** @hidden */
  24663. Scene.prototype.getInterFramePerfCounter = function () {
  24664. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24665. return 0;
  24666. };
  24667. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24668. /** @hidden */
  24669. get: function () {
  24670. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24671. return null;
  24672. },
  24673. enumerable: true,
  24674. configurable: true
  24675. });
  24676. /** @hidden */
  24677. Scene.prototype.getLastFrameDuration = function () {
  24678. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24679. return 0;
  24680. };
  24681. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24682. /** @hidden */
  24683. get: function () {
  24684. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24685. return null;
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. /** @hidden */
  24691. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24692. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24693. return 0;
  24694. };
  24695. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24696. /** @hidden */
  24697. get: function () {
  24698. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24699. return null;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. /**
  24705. * Gets the array of active meshes
  24706. * @returns an array of AbstractMesh
  24707. */
  24708. Scene.prototype.getActiveMeshes = function () {
  24709. return this._activeMeshes;
  24710. };
  24711. /** @hidden */
  24712. Scene.prototype.getRenderTargetsDuration = function () {
  24713. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24714. return 0;
  24715. };
  24716. /** @hidden */
  24717. Scene.prototype.getRenderDuration = function () {
  24718. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24719. return 0;
  24720. };
  24721. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24722. /** @hidden */
  24723. get: function () {
  24724. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24725. return null;
  24726. },
  24727. enumerable: true,
  24728. configurable: true
  24729. });
  24730. /** @hidden */
  24731. Scene.prototype.getParticlesDuration = function () {
  24732. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24733. return 0;
  24734. };
  24735. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24736. /** @hidden */
  24737. get: function () {
  24738. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24739. return null;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. /** @hidden */
  24745. Scene.prototype.getSpritesDuration = function () {
  24746. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24747. return 0;
  24748. };
  24749. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24750. /** @hidden */
  24751. get: function () {
  24752. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24753. return null;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. /**
  24759. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24760. * @returns a number
  24761. */
  24762. Scene.prototype.getAnimationRatio = function () {
  24763. return this._animationRatio;
  24764. };
  24765. /**
  24766. * Gets an unique Id for the current frame
  24767. * @returns a number
  24768. */
  24769. Scene.prototype.getRenderId = function () {
  24770. return this._renderId;
  24771. };
  24772. /** Call this function if you want to manually increment the render Id*/
  24773. Scene.prototype.incrementRenderId = function () {
  24774. this._renderId++;
  24775. };
  24776. Scene.prototype._updatePointerPosition = function (evt) {
  24777. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24778. if (!canvasRect) {
  24779. return;
  24780. }
  24781. this._pointerX = evt.clientX - canvasRect.left;
  24782. this._pointerY = evt.clientY - canvasRect.top;
  24783. this._unTranslatedPointerX = this._pointerX;
  24784. this._unTranslatedPointerY = this._pointerY;
  24785. };
  24786. Scene.prototype._createUbo = function () {
  24787. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24788. this._sceneUbo.addUniform("viewProjection", 16);
  24789. this._sceneUbo.addUniform("view", 16);
  24790. };
  24791. Scene.prototype._createAlternateUbo = function () {
  24792. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24793. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24794. this._alternateSceneUbo.addUniform("view", 16);
  24795. };
  24796. // Pointers handling
  24797. /**
  24798. * Use this method to simulate a pointer move on a mesh
  24799. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24800. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24801. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24802. * @returns the current scene
  24803. */
  24804. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24805. var evt = new PointerEvent("pointermove", pointerEventInit);
  24806. return this._processPointerMove(pickResult, evt);
  24807. };
  24808. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24809. var canvas = this._engine.getRenderingCanvas();
  24810. if (!canvas) {
  24811. return this;
  24812. }
  24813. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24814. this.setPointerOverSprite(null);
  24815. this.setPointerOverMesh(pickResult.pickedMesh);
  24816. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24817. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24818. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24819. }
  24820. else {
  24821. canvas.style.cursor = this.hoverCursor;
  24822. }
  24823. }
  24824. else {
  24825. canvas.style.cursor = this.defaultCursor;
  24826. }
  24827. }
  24828. else {
  24829. this.setPointerOverMesh(null);
  24830. // Sprites
  24831. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24832. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24833. this.setPointerOverSprite(pickResult.pickedSprite);
  24834. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24835. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24836. }
  24837. else {
  24838. canvas.style.cursor = this.hoverCursor;
  24839. }
  24840. }
  24841. else {
  24842. this.setPointerOverSprite(null);
  24843. // Restore pointer
  24844. canvas.style.cursor = this.defaultCursor;
  24845. }
  24846. }
  24847. if (pickResult) {
  24848. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24849. if (this.onPointerMove) {
  24850. this.onPointerMove(evt, pickResult, type);
  24851. }
  24852. if (this.onPointerObservable.hasObservers()) {
  24853. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24854. this.onPointerObservable.notifyObservers(pi, type);
  24855. }
  24856. }
  24857. return this;
  24858. };
  24859. /**
  24860. * Use this method to simulate a pointer down on a mesh
  24861. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24862. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24863. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24864. * @returns the current scene
  24865. */
  24866. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24867. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24868. return this._processPointerDown(pickResult, evt);
  24869. };
  24870. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24871. var _this = this;
  24872. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24873. this._pickedDownMesh = pickResult.pickedMesh;
  24874. var actionManager = pickResult.pickedMesh.actionManager;
  24875. if (actionManager) {
  24876. if (actionManager.hasPickTriggers) {
  24877. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24878. switch (evt.button) {
  24879. case 0:
  24880. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24881. break;
  24882. case 1:
  24883. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24884. break;
  24885. case 2:
  24886. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24887. break;
  24888. }
  24889. }
  24890. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24891. window.setTimeout(function () {
  24892. 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);
  24893. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24894. if (_this._totalPointersPressed !== 0 &&
  24895. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24896. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24897. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24898. _this._startingPointerTime = 0;
  24899. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24900. }
  24901. }
  24902. }, Scene.LongPressDelay);
  24903. }
  24904. }
  24905. }
  24906. if (pickResult) {
  24907. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24908. if (this.onPointerDown) {
  24909. this.onPointerDown(evt, pickResult, type);
  24910. }
  24911. if (this.onPointerObservable.hasObservers()) {
  24912. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24913. this.onPointerObservable.notifyObservers(pi, type);
  24914. }
  24915. }
  24916. return this;
  24917. };
  24918. /**
  24919. * Use this method to simulate a pointer up on a mesh
  24920. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24921. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24922. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24923. * @returns the current scene
  24924. */
  24925. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24926. var evt = new PointerEvent("pointerup", pointerEventInit);
  24927. var clickInfo = new ClickInfo();
  24928. clickInfo.singleClick = true;
  24929. clickInfo.ignore = true;
  24930. return this._processPointerUp(pickResult, evt, clickInfo);
  24931. };
  24932. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24933. if (pickResult && pickResult && pickResult.pickedMesh) {
  24934. this._pickedUpMesh = pickResult.pickedMesh;
  24935. if (this._pickedDownMesh === this._pickedUpMesh) {
  24936. if (this.onPointerPick) {
  24937. this.onPointerPick(evt, pickResult);
  24938. }
  24939. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24940. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24941. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24942. this.onPointerObservable.notifyObservers(pi, type_1);
  24943. }
  24944. }
  24945. if (pickResult.pickedMesh.actionManager) {
  24946. if (clickInfo.ignore) {
  24947. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24948. }
  24949. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24950. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24951. }
  24952. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24953. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24954. }
  24955. }
  24956. }
  24957. if (this._pickedDownMesh &&
  24958. this._pickedDownMesh.actionManager &&
  24959. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24960. this._pickedDownMesh !== this._pickedUpMesh) {
  24961. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24962. }
  24963. var type = BABYLON.PointerEventTypes.POINTERUP;
  24964. if (this.onPointerObservable.hasObservers()) {
  24965. if (!clickInfo.ignore) {
  24966. if (!clickInfo.hasSwiped) {
  24967. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24968. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24969. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24970. this.onPointerObservable.notifyObservers(pi, type_2);
  24971. }
  24972. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24973. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24974. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24975. this.onPointerObservable.notifyObservers(pi, type_3);
  24976. }
  24977. }
  24978. }
  24979. else {
  24980. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24981. this.onPointerObservable.notifyObservers(pi, type);
  24982. }
  24983. }
  24984. if (this.onPointerUp) {
  24985. this.onPointerUp(evt, pickResult, type);
  24986. }
  24987. return this;
  24988. };
  24989. /**
  24990. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24991. * @param attachUp defines if you want to attach events to pointerup
  24992. * @param attachDown defines if you want to attach events to pointerdown
  24993. * @param attachMove defines if you want to attach events to pointermove
  24994. */
  24995. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24996. var _this = this;
  24997. if (attachUp === void 0) { attachUp = true; }
  24998. if (attachDown === void 0) { attachDown = true; }
  24999. if (attachMove === void 0) { attachMove = true; }
  25000. this._initActionManager = function (act, clickInfo) {
  25001. if (!_this._meshPickProceed) {
  25002. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25003. _this._currentPickResult = pickResult;
  25004. if (pickResult) {
  25005. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25006. }
  25007. _this._meshPickProceed = true;
  25008. }
  25009. return act;
  25010. };
  25011. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25012. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25013. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25014. btn !== _this._previousButtonPressed) {
  25015. _this._doubleClickOccured = false;
  25016. clickInfo.singleClick = true;
  25017. clickInfo.ignore = false;
  25018. cb(clickInfo, _this._currentPickResult);
  25019. }
  25020. };
  25021. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25022. var clickInfo = new ClickInfo();
  25023. _this._currentPickResult = null;
  25024. var act = null;
  25025. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25026. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25027. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25028. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25029. act = _this._initActionManager(act, clickInfo);
  25030. if (act)
  25031. checkPicking = act.hasPickTriggers;
  25032. }
  25033. if (checkPicking) {
  25034. var btn = evt.button;
  25035. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25036. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25037. if (!clickInfo.hasSwiped) {
  25038. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25039. if (!checkSingleClickImmediately) {
  25040. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25041. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25042. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25043. act = _this._initActionManager(act, clickInfo);
  25044. if (act)
  25045. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25046. }
  25047. }
  25048. if (checkSingleClickImmediately) {
  25049. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25050. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25051. btn !== _this._previousButtonPressed) {
  25052. clickInfo.singleClick = true;
  25053. cb(clickInfo, _this._currentPickResult);
  25054. }
  25055. }
  25056. // at least one double click is required to be check and exclusive double click is enabled
  25057. else {
  25058. // wait that no double click has been raised during the double click delay
  25059. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25060. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25061. }
  25062. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25063. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25064. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25065. act = _this._initActionManager(act, clickInfo);
  25066. if (act)
  25067. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25068. }
  25069. if (checkDoubleClick) {
  25070. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25071. if (btn === _this._previousButtonPressed &&
  25072. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25073. !_this._doubleClickOccured) {
  25074. // pointer has not moved for 2 clicks, it's a double click
  25075. if (!clickInfo.hasSwiped &&
  25076. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25077. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25078. _this._previousStartingPointerTime = 0;
  25079. _this._doubleClickOccured = true;
  25080. clickInfo.doubleClick = true;
  25081. clickInfo.ignore = false;
  25082. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25083. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25084. }
  25085. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25086. cb(clickInfo, _this._currentPickResult);
  25087. }
  25088. // if the two successive clicks are too far, it's just two simple clicks
  25089. else {
  25090. _this._doubleClickOccured = false;
  25091. _this._previousStartingPointerTime = _this._startingPointerTime;
  25092. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25093. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25094. _this._previousButtonPressed = btn;
  25095. if (Scene.ExclusiveDoubleClickMode) {
  25096. if (_this._previousDelayedSimpleClickTimeout) {
  25097. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25098. }
  25099. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25100. cb(clickInfo, _this._previousPickResult);
  25101. }
  25102. else {
  25103. cb(clickInfo, _this._currentPickResult);
  25104. }
  25105. }
  25106. }
  25107. // just the first click of the double has been raised
  25108. else {
  25109. _this._doubleClickOccured = false;
  25110. _this._previousStartingPointerTime = _this._startingPointerTime;
  25111. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25112. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25113. _this._previousButtonPressed = btn;
  25114. }
  25115. }
  25116. }
  25117. }
  25118. clickInfo.ignore = true;
  25119. cb(clickInfo, _this._currentPickResult);
  25120. };
  25121. this._spritePredicate = function (sprite) {
  25122. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25123. };
  25124. this._onPointerMove = function (evt) {
  25125. _this._updatePointerPosition(evt);
  25126. // PreObservable support
  25127. if (_this.onPrePointerObservable.hasObservers()) {
  25128. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25129. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25130. _this.onPrePointerObservable.notifyObservers(pi, type);
  25131. if (pi.skipOnPointerObservable) {
  25132. return;
  25133. }
  25134. }
  25135. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25136. return;
  25137. }
  25138. if (!_this.pointerMovePredicate) {
  25139. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25140. }
  25141. // Meshes
  25142. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25143. _this._processPointerMove(pickResult, evt);
  25144. };
  25145. this._onPointerDown = function (evt) {
  25146. _this._totalPointersPressed++;
  25147. _this._pickedDownMesh = null;
  25148. _this._meshPickProceed = false;
  25149. _this._updatePointerPosition(evt);
  25150. if (_this.preventDefaultOnPointerDown && canvas) {
  25151. evt.preventDefault();
  25152. canvas.focus();
  25153. }
  25154. // PreObservable support
  25155. if (_this.onPrePointerObservable.hasObservers()) {
  25156. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25157. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25158. _this.onPrePointerObservable.notifyObservers(pi, type);
  25159. if (pi.skipOnPointerObservable) {
  25160. return;
  25161. }
  25162. }
  25163. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25164. return;
  25165. }
  25166. _this._startingPointerPosition.x = _this._pointerX;
  25167. _this._startingPointerPosition.y = _this._pointerY;
  25168. _this._startingPointerTime = Date.now();
  25169. if (!_this.pointerDownPredicate) {
  25170. _this.pointerDownPredicate = function (mesh) {
  25171. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25172. };
  25173. }
  25174. // Meshes
  25175. _this._pickedDownMesh = null;
  25176. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25177. _this._processPointerDown(pickResult, evt);
  25178. // Sprites
  25179. _this._pickedDownSprite = null;
  25180. if (_this.spriteManagers.length > 0) {
  25181. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25182. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25183. if (pickResult.pickedSprite.actionManager) {
  25184. _this._pickedDownSprite = pickResult.pickedSprite;
  25185. switch (evt.button) {
  25186. case 0:
  25187. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25188. break;
  25189. case 1:
  25190. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25191. break;
  25192. case 2:
  25193. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25194. break;
  25195. }
  25196. if (pickResult.pickedSprite.actionManager) {
  25197. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25198. }
  25199. }
  25200. }
  25201. }
  25202. };
  25203. this._onPointerUp = function (evt) {
  25204. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25205. return; // So we need to test it the pointer down was pressed before.
  25206. }
  25207. _this._totalPointersPressed--;
  25208. _this._pickedUpMesh = null;
  25209. _this._meshPickProceed = false;
  25210. _this._updatePointerPosition(evt);
  25211. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25212. // PreObservable support
  25213. if (_this.onPrePointerObservable.hasObservers()) {
  25214. if (!clickInfo.ignore) {
  25215. if (!clickInfo.hasSwiped) {
  25216. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25217. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25218. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25219. _this.onPrePointerObservable.notifyObservers(pi, type);
  25220. if (pi.skipOnPointerObservable) {
  25221. return;
  25222. }
  25223. }
  25224. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25225. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25226. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25227. _this.onPrePointerObservable.notifyObservers(pi, type);
  25228. if (pi.skipOnPointerObservable) {
  25229. return;
  25230. }
  25231. }
  25232. }
  25233. }
  25234. else {
  25235. var type = BABYLON.PointerEventTypes.POINTERUP;
  25236. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25237. _this.onPrePointerObservable.notifyObservers(pi, type);
  25238. if (pi.skipOnPointerObservable) {
  25239. return;
  25240. }
  25241. }
  25242. }
  25243. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25244. return;
  25245. }
  25246. if (!_this.pointerUpPredicate) {
  25247. _this.pointerUpPredicate = function (mesh) {
  25248. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25249. };
  25250. }
  25251. // Meshes
  25252. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25253. _this._initActionManager(null, clickInfo);
  25254. }
  25255. if (!pickResult) {
  25256. pickResult = _this._currentPickResult;
  25257. }
  25258. _this._processPointerUp(pickResult, evt, clickInfo);
  25259. // Sprites
  25260. if (_this.spriteManagers.length > 0) {
  25261. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25262. if (spritePickResult) {
  25263. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25264. if (spritePickResult.pickedSprite.actionManager) {
  25265. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25266. if (spritePickResult.pickedSprite.actionManager) {
  25267. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25268. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25269. }
  25270. }
  25271. }
  25272. }
  25273. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25274. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25275. }
  25276. }
  25277. }
  25278. _this._previousPickResult = _this._currentPickResult;
  25279. });
  25280. };
  25281. this._onKeyDown = function (evt) {
  25282. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25283. if (_this.onPreKeyboardObservable.hasObservers()) {
  25284. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25285. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25286. if (pi.skipOnPointerObservable) {
  25287. return;
  25288. }
  25289. }
  25290. if (_this.onKeyboardObservable.hasObservers()) {
  25291. var pi = new BABYLON.KeyboardInfo(type, evt);
  25292. _this.onKeyboardObservable.notifyObservers(pi, type);
  25293. }
  25294. if (_this.actionManager) {
  25295. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25296. }
  25297. };
  25298. this._onKeyUp = function (evt) {
  25299. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25300. if (_this.onPreKeyboardObservable.hasObservers()) {
  25301. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25302. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25303. if (pi.skipOnPointerObservable) {
  25304. return;
  25305. }
  25306. }
  25307. if (_this.onKeyboardObservable.hasObservers()) {
  25308. var pi = new BABYLON.KeyboardInfo(type, evt);
  25309. _this.onKeyboardObservable.notifyObservers(pi, type);
  25310. }
  25311. if (_this.actionManager) {
  25312. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25313. }
  25314. };
  25315. var engine = this.getEngine();
  25316. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25317. if (!canvas) {
  25318. return;
  25319. }
  25320. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25321. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25322. });
  25323. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25324. if (!canvas) {
  25325. return;
  25326. }
  25327. canvas.removeEventListener("keydown", _this._onKeyDown);
  25328. canvas.removeEventListener("keyup", _this._onKeyUp);
  25329. });
  25330. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25331. var canvas = this._engine.getRenderingCanvas();
  25332. if (!canvas) {
  25333. return;
  25334. }
  25335. if (attachMove) {
  25336. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25337. // Wheel
  25338. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25339. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25340. }
  25341. if (attachDown) {
  25342. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25343. }
  25344. if (attachUp) {
  25345. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25346. }
  25347. canvas.tabIndex = 1;
  25348. };
  25349. /** Detaches all event handlers*/
  25350. Scene.prototype.detachControl = function () {
  25351. var engine = this.getEngine();
  25352. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25353. var canvas = engine.getRenderingCanvas();
  25354. if (!canvas) {
  25355. return;
  25356. }
  25357. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25358. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25359. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25360. if (this._onCanvasBlurObserver) {
  25361. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25362. }
  25363. if (this._onCanvasFocusObserver) {
  25364. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25365. }
  25366. // Wheel
  25367. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25368. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25369. // Keyboard
  25370. canvas.removeEventListener("keydown", this._onKeyDown);
  25371. canvas.removeEventListener("keyup", this._onKeyUp);
  25372. // Observables
  25373. this.onKeyboardObservable.clear();
  25374. this.onPreKeyboardObservable.clear();
  25375. this.onPointerObservable.clear();
  25376. this.onPrePointerObservable.clear();
  25377. };
  25378. /**
  25379. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25380. * Delay loaded resources are not taking in account
  25381. * @return true if all required resources are ready
  25382. */
  25383. Scene.prototype.isReady = function () {
  25384. if (this._isDisposed) {
  25385. return false;
  25386. }
  25387. if (this._pendingData.length > 0) {
  25388. return false;
  25389. }
  25390. var index;
  25391. var engine = this.getEngine();
  25392. // Geometries
  25393. for (index = 0; index < this._geometries.length; index++) {
  25394. var geometry = this._geometries[index];
  25395. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25396. return false;
  25397. }
  25398. }
  25399. // Meshes
  25400. for (index = 0; index < this.meshes.length; index++) {
  25401. var mesh = this.meshes[index];
  25402. if (!mesh.isEnabled()) {
  25403. continue;
  25404. }
  25405. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25406. continue;
  25407. }
  25408. if (!mesh.isReady(true)) {
  25409. return false;
  25410. }
  25411. // Effect layers
  25412. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25413. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25414. var layer = _a[_i];
  25415. if (!layer.hasMesh(mesh)) {
  25416. continue;
  25417. }
  25418. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25419. var subMesh = _c[_b];
  25420. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25421. return false;
  25422. }
  25423. }
  25424. }
  25425. }
  25426. // Post-processes
  25427. if (this.activeCameras && this.activeCameras.length > 0) {
  25428. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25429. var camera = _e[_d];
  25430. if (!camera.isReady(true)) {
  25431. return false;
  25432. }
  25433. }
  25434. }
  25435. else if (this.activeCamera) {
  25436. if (!this.activeCamera.isReady(true)) {
  25437. return false;
  25438. }
  25439. }
  25440. // Particles
  25441. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25442. var particleSystem = _g[_f];
  25443. if (!particleSystem.isReady()) {
  25444. return false;
  25445. }
  25446. }
  25447. return true;
  25448. };
  25449. /** Resets all cached information relative to material (including effect and visibility) */
  25450. Scene.prototype.resetCachedMaterial = function () {
  25451. this._cachedMaterial = null;
  25452. this._cachedEffect = null;
  25453. this._cachedVisibility = null;
  25454. };
  25455. /**
  25456. * Registers a function to be called before every frame render
  25457. * @param func defines the function to register
  25458. */
  25459. Scene.prototype.registerBeforeRender = function (func) {
  25460. this.onBeforeRenderObservable.add(func);
  25461. };
  25462. /**
  25463. * Unregisters a function called before every frame render
  25464. * @param func defines the function to unregister
  25465. */
  25466. Scene.prototype.unregisterBeforeRender = function (func) {
  25467. this.onBeforeRenderObservable.removeCallback(func);
  25468. };
  25469. /**
  25470. * Registers a function to be called after every frame render
  25471. * @param func defines the function to register
  25472. */
  25473. Scene.prototype.registerAfterRender = function (func) {
  25474. this.onAfterRenderObservable.add(func);
  25475. };
  25476. /**
  25477. * Unregisters a function called after every frame render
  25478. * @param func defines the function to unregister
  25479. */
  25480. Scene.prototype.unregisterAfterRender = function (func) {
  25481. this.onAfterRenderObservable.removeCallback(func);
  25482. };
  25483. Scene.prototype._executeOnceBeforeRender = function (func) {
  25484. var _this = this;
  25485. var execFunc = function () {
  25486. func();
  25487. setTimeout(function () {
  25488. _this.unregisterBeforeRender(execFunc);
  25489. });
  25490. };
  25491. this.registerBeforeRender(execFunc);
  25492. };
  25493. /**
  25494. * The provided function will run before render once and will be disposed afterwards.
  25495. * A timeout delay can be provided so that the function will be executed in N ms.
  25496. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25497. * @param func The function to be executed.
  25498. * @param timeout optional delay in ms
  25499. */
  25500. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25501. var _this = this;
  25502. if (timeout !== undefined) {
  25503. setTimeout(function () {
  25504. _this._executeOnceBeforeRender(func);
  25505. }, timeout);
  25506. }
  25507. else {
  25508. this._executeOnceBeforeRender(func);
  25509. }
  25510. };
  25511. /** @hidden */
  25512. Scene.prototype._addPendingData = function (data) {
  25513. this._pendingData.push(data);
  25514. };
  25515. /** @hidden */
  25516. Scene.prototype._removePendingData = function (data) {
  25517. var wasLoading = this.isLoading;
  25518. var index = this._pendingData.indexOf(data);
  25519. if (index !== -1) {
  25520. this._pendingData.splice(index, 1);
  25521. }
  25522. if (wasLoading && !this.isLoading) {
  25523. this.onDataLoadedObservable.notifyObservers(this);
  25524. }
  25525. };
  25526. /**
  25527. * Returns the number of items waiting to be loaded
  25528. * @returns the number of items waiting to be loaded
  25529. */
  25530. Scene.prototype.getWaitingItemsCount = function () {
  25531. return this._pendingData.length;
  25532. };
  25533. Object.defineProperty(Scene.prototype, "isLoading", {
  25534. /**
  25535. * Returns a boolean indicating if the scene is still loading data
  25536. */
  25537. get: function () {
  25538. return this._pendingData.length > 0;
  25539. },
  25540. enumerable: true,
  25541. configurable: true
  25542. });
  25543. /**
  25544. * Registers a function to be executed when the scene is ready
  25545. * @param {Function} func - the function to be executed
  25546. */
  25547. Scene.prototype.executeWhenReady = function (func) {
  25548. var _this = this;
  25549. this.onReadyObservable.add(func);
  25550. if (this._executeWhenReadyTimeoutId !== -1) {
  25551. return;
  25552. }
  25553. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25554. _this._checkIsReady();
  25555. }, 150);
  25556. };
  25557. /**
  25558. * Returns a promise that resolves when the scene is ready
  25559. * @returns A promise that resolves when the scene is ready
  25560. */
  25561. Scene.prototype.whenReadyAsync = function () {
  25562. var _this = this;
  25563. return new Promise(function (resolve) {
  25564. _this.executeWhenReady(function () {
  25565. resolve();
  25566. });
  25567. });
  25568. };
  25569. /** @hidden */
  25570. Scene.prototype._checkIsReady = function () {
  25571. var _this = this;
  25572. if (this.isReady()) {
  25573. this.onReadyObservable.notifyObservers(this);
  25574. this.onReadyObservable.clear();
  25575. this._executeWhenReadyTimeoutId = -1;
  25576. return;
  25577. }
  25578. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25579. _this._checkIsReady();
  25580. }, 150);
  25581. };
  25582. // Animations
  25583. /**
  25584. * Will start the animation sequence of a given target
  25585. * @param target defines the target
  25586. * @param from defines from which frame should animation start
  25587. * @param to defines until which frame should animation run.
  25588. * @param weight defines the weight to apply to the animation (1.0 by default)
  25589. * @param loop defines if the animation loops
  25590. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25591. * @param onAnimationEnd defines the function to be executed when the animation ends
  25592. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25593. * @returns the animatable object created for this animation
  25594. */
  25595. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25596. if (weight === void 0) { weight = 1.0; }
  25597. if (speedRatio === void 0) { speedRatio = 1.0; }
  25598. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25599. returnedAnimatable.weight = weight;
  25600. return returnedAnimatable;
  25601. };
  25602. /**
  25603. * Will start the animation sequence of a given target
  25604. * @param target defines the target
  25605. * @param from defines from which frame should animation start
  25606. * @param to defines until which frame should animation run.
  25607. * @param loop defines if the animation loops
  25608. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25609. * @param onAnimationEnd defines the function to be executed when the animation ends
  25610. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25611. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25612. * @returns the animatable object created for this animation
  25613. */
  25614. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25615. if (speedRatio === void 0) { speedRatio = 1.0; }
  25616. if (stopCurrent === void 0) { stopCurrent = true; }
  25617. if (from > to && speedRatio > 0) {
  25618. speedRatio *= -1;
  25619. }
  25620. if (stopCurrent) {
  25621. this.stopAnimation(target);
  25622. }
  25623. if (!animatable) {
  25624. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25625. }
  25626. // Local animations
  25627. if (target.animations) {
  25628. animatable.appendAnimations(target, target.animations);
  25629. }
  25630. // Children animations
  25631. if (target.getAnimatables) {
  25632. var animatables = target.getAnimatables();
  25633. for (var index = 0; index < animatables.length; index++) {
  25634. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25635. }
  25636. }
  25637. animatable.reset();
  25638. return animatable;
  25639. };
  25640. /**
  25641. * Begin a new animation on a given node
  25642. * @param target defines the target where the animation will take place
  25643. * @param animations defines the list of animations to start
  25644. * @param from defines the initial value
  25645. * @param to defines the final value
  25646. * @param loop defines if you want animation to loop (off by default)
  25647. * @param speedRatio defines the speed ratio to apply to all animations
  25648. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25649. * @returns the list of created animatables
  25650. */
  25651. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25652. if (speedRatio === undefined) {
  25653. speedRatio = 1.0;
  25654. }
  25655. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25656. return animatable;
  25657. };
  25658. /**
  25659. * Begin a new animation on a given node and its hierarchy
  25660. * @param target defines the root node where the animation will take place
  25661. * @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.
  25662. * @param animations defines the list of animations to start
  25663. * @param from defines the initial value
  25664. * @param to defines the final value
  25665. * @param loop defines if you want animation to loop (off by default)
  25666. * @param speedRatio defines the speed ratio to apply to all animations
  25667. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25668. * @returns the list of animatables created for all nodes
  25669. */
  25670. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25671. var children = target.getDescendants(directDescendantsOnly);
  25672. var result = [];
  25673. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25674. var child = children_1[_i];
  25675. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25676. }
  25677. return result;
  25678. };
  25679. /**
  25680. * Gets the animatable associated with a specific target
  25681. * @param target defines the target of the animatable
  25682. * @returns the required animatable if found
  25683. */
  25684. Scene.prototype.getAnimatableByTarget = function (target) {
  25685. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25686. if (this._activeAnimatables[index].target === target) {
  25687. return this._activeAnimatables[index];
  25688. }
  25689. }
  25690. return null;
  25691. };
  25692. /**
  25693. * Gets all animatables associated with a given target
  25694. * @param target defines the target to look animatables for
  25695. * @returns an array of Animatables
  25696. */
  25697. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25698. var result = [];
  25699. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25700. if (this._activeAnimatables[index].target === target) {
  25701. result.push(this._activeAnimatables[index]);
  25702. }
  25703. }
  25704. return result;
  25705. };
  25706. Object.defineProperty(Scene.prototype, "animatables", {
  25707. /**
  25708. * Gets all animatable attached to the scene
  25709. */
  25710. get: function () {
  25711. return this._activeAnimatables;
  25712. },
  25713. enumerable: true,
  25714. configurable: true
  25715. });
  25716. /**
  25717. * Will stop the animation of the given target
  25718. * @param target - the target
  25719. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25720. */
  25721. Scene.prototype.stopAnimation = function (target, animationName) {
  25722. var animatables = this.getAllAnimatablesByTarget(target);
  25723. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25724. var animatable = animatables_1[_i];
  25725. animatable.stop(animationName);
  25726. }
  25727. };
  25728. /**
  25729. * Stops and removes all animations that have been applied to the scene
  25730. */
  25731. Scene.prototype.stopAllAnimations = function () {
  25732. if (this._activeAnimatables) {
  25733. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25734. this._activeAnimatables[i].stop();
  25735. }
  25736. this._activeAnimatables = [];
  25737. }
  25738. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25739. var group = _a[_i];
  25740. group.stop();
  25741. }
  25742. };
  25743. Scene.prototype._animate = function () {
  25744. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25745. return;
  25746. }
  25747. // Getting time
  25748. var now = BABYLON.Tools.Now;
  25749. if (!this._animationTimeLast) {
  25750. if (this._pendingData.length > 0) {
  25751. return;
  25752. }
  25753. this._animationTimeLast = now;
  25754. }
  25755. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25756. this._animationTime += deltaTime;
  25757. this._animationTimeLast = now;
  25758. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25759. this._activeAnimatables[index]._animate(this._animationTime);
  25760. }
  25761. // Late animation bindings
  25762. this._processLateAnimationBindings();
  25763. };
  25764. /** @hidden */
  25765. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25766. var target = runtimeAnimation.target;
  25767. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25768. if (!target._lateAnimationHolders) {
  25769. target._lateAnimationHolders = {};
  25770. }
  25771. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25772. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25773. totalWeight: 0,
  25774. animations: []
  25775. };
  25776. }
  25777. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25778. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25779. };
  25780. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25781. var normalizer = 1.0;
  25782. var finalPosition = BABYLON.Tmp.Vector3[0];
  25783. var finalScaling = BABYLON.Tmp.Vector3[1];
  25784. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25785. var startIndex = 0;
  25786. var originalAnimation = holder.animations[0];
  25787. var scale = 1;
  25788. if (holder.totalWeight < 1.0) {
  25789. // We need to mix the original value in
  25790. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25791. scale = 1.0 - holder.totalWeight;
  25792. }
  25793. else {
  25794. startIndex = 1;
  25795. // We need to normalize the weights
  25796. normalizer = holder.totalWeight;
  25797. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25798. scale = originalAnimation.weight / normalizer;
  25799. if (scale == 1) {
  25800. return originalAnimation.currentValue;
  25801. }
  25802. }
  25803. finalScaling.scaleInPlace(scale);
  25804. finalPosition.scaleInPlace(scale);
  25805. finalQuaternion.scaleInPlace(scale);
  25806. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25807. var runtimeAnimation = holder.animations[animIndex];
  25808. var scale = runtimeAnimation.weight / normalizer;
  25809. var currentPosition = BABYLON.Tmp.Vector3[2];
  25810. var currentScaling = BABYLON.Tmp.Vector3[3];
  25811. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25812. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25813. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25814. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25815. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25816. }
  25817. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25818. return originalAnimation._workValue;
  25819. };
  25820. Scene.prototype._processLateAnimationBindings = function () {
  25821. if (!this._registeredForLateAnimationBindings.length) {
  25822. return;
  25823. }
  25824. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25825. var target = this._registeredForLateAnimationBindings.data[index];
  25826. for (var path in target._lateAnimationHolders) {
  25827. var holder = target._lateAnimationHolders[path];
  25828. var originalAnimation = holder.animations[0];
  25829. var originalValue = originalAnimation.originalValue;
  25830. var finalTarget = originalAnimation.target;
  25831. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25832. var finalValue = void 0;
  25833. if (matrixDecomposeMode) {
  25834. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25835. }
  25836. else {
  25837. var startIndex = 0;
  25838. var normalizer = 1.0;
  25839. if (holder.totalWeight < 1.0) {
  25840. // We need to mix the original value in
  25841. if (originalValue.scale) {
  25842. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25843. }
  25844. else {
  25845. finalValue = originalValue * (1.0 - holder.totalWeight);
  25846. }
  25847. }
  25848. else {
  25849. // We need to normalize the weights
  25850. normalizer = holder.totalWeight;
  25851. var scale_1 = originalAnimation.weight / normalizer;
  25852. if (scale_1 !== 1) {
  25853. if (originalAnimation.currentValue.scale) {
  25854. finalValue = originalAnimation.currentValue.scale(scale_1);
  25855. }
  25856. else {
  25857. finalValue = originalAnimation.currentValue * scale_1;
  25858. }
  25859. }
  25860. else {
  25861. finalValue = originalAnimation.currentValue;
  25862. }
  25863. startIndex = 1;
  25864. }
  25865. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25866. var runtimeAnimation = holder.animations[animIndex];
  25867. var scale = runtimeAnimation.weight / normalizer;
  25868. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25869. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25870. }
  25871. else {
  25872. finalValue += runtimeAnimation.currentValue * scale;
  25873. }
  25874. }
  25875. }
  25876. finalTarget[path] = finalValue;
  25877. }
  25878. target._lateAnimationHolders = {};
  25879. }
  25880. this._registeredForLateAnimationBindings.reset();
  25881. };
  25882. // Matrix
  25883. /** @hidden */
  25884. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25885. this._useAlternateCameraConfiguration = active;
  25886. };
  25887. /**
  25888. * Gets the current view matrix
  25889. * @returns a Matrix
  25890. */
  25891. Scene.prototype.getViewMatrix = function () {
  25892. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25893. };
  25894. /**
  25895. * Gets the current projection matrix
  25896. * @returns a Matrix
  25897. */
  25898. Scene.prototype.getProjectionMatrix = function () {
  25899. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25900. };
  25901. /**
  25902. * Gets the current transform matrix
  25903. * @returns a Matrix made of View * Projection
  25904. */
  25905. Scene.prototype.getTransformMatrix = function () {
  25906. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25907. };
  25908. /**
  25909. * Sets the current transform matrix
  25910. * @param view defines the View matrix to use
  25911. * @param projection defines the Projection matrix to use
  25912. */
  25913. Scene.prototype.setTransformMatrix = function (view, projection) {
  25914. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25915. return;
  25916. }
  25917. this._viewUpdateFlag = view.updateFlag;
  25918. this._projectionUpdateFlag = projection.updateFlag;
  25919. this._viewMatrix = view;
  25920. this._projectionMatrix = projection;
  25921. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25922. // Update frustum
  25923. if (!this._frustumPlanes) {
  25924. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25925. }
  25926. else {
  25927. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25928. }
  25929. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25930. var otherCamera = this.activeCamera._alternateCamera;
  25931. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25932. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25933. }
  25934. if (this._sceneUbo.useUbo) {
  25935. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25936. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25937. this._sceneUbo.update();
  25938. }
  25939. };
  25940. /** @hidden */
  25941. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25942. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25943. return;
  25944. }
  25945. this._alternateViewUpdateFlag = view.updateFlag;
  25946. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25947. this._alternateViewMatrix = view;
  25948. this._alternateProjectionMatrix = projection;
  25949. if (!this._alternateTransformMatrix) {
  25950. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25951. }
  25952. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25953. if (!this._alternateSceneUbo) {
  25954. this._createAlternateUbo();
  25955. }
  25956. if (this._alternateSceneUbo.useUbo) {
  25957. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25958. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25959. this._alternateSceneUbo.update();
  25960. }
  25961. };
  25962. /**
  25963. * Gets the uniform buffer used to store scene data
  25964. * @returns a UniformBuffer
  25965. */
  25966. Scene.prototype.getSceneUniformBuffer = function () {
  25967. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25968. };
  25969. /**
  25970. * Gets an unique (relatively to the current scene) Id
  25971. * @returns an unique number for the scene
  25972. */
  25973. Scene.prototype.getUniqueId = function () {
  25974. var result = Scene._uniqueIdCounter;
  25975. Scene._uniqueIdCounter++;
  25976. return result;
  25977. };
  25978. /**
  25979. * Add a mesh to the list of scene's meshes
  25980. * @param newMesh defines the mesh to add
  25981. */
  25982. Scene.prototype.addMesh = function (newMesh) {
  25983. this.meshes.push(newMesh);
  25984. //notify the collision coordinator
  25985. if (this.collisionCoordinator) {
  25986. this.collisionCoordinator.onMeshAdded(newMesh);
  25987. }
  25988. newMesh._resyncLightSources();
  25989. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25990. };
  25991. /**
  25992. * Remove a mesh for the list of scene's meshes
  25993. * @param toRemove defines the mesh to remove
  25994. * @returns the index where the mesh was in the mesh list
  25995. */
  25996. Scene.prototype.removeMesh = function (toRemove) {
  25997. var index = this.meshes.indexOf(toRemove);
  25998. if (index !== -1) {
  25999. // Remove from the scene if mesh found
  26000. this.meshes.splice(index, 1);
  26001. }
  26002. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26003. return index;
  26004. };
  26005. /**
  26006. * Add a transform node to the list of scene's transform nodes
  26007. * @param newTransformNode defines the transform node to add
  26008. */
  26009. Scene.prototype.addTransformNode = function (newTransformNode) {
  26010. this.transformNodes.push(newTransformNode);
  26011. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26012. };
  26013. /**
  26014. * Remove a transform node for the list of scene's transform nodes
  26015. * @param toRemove defines the transform node to remove
  26016. * @returns the index where the transform node was in the transform node list
  26017. */
  26018. Scene.prototype.removeTransformNode = function (toRemove) {
  26019. var index = this.transformNodes.indexOf(toRemove);
  26020. if (index !== -1) {
  26021. // Remove from the scene if found
  26022. this.transformNodes.splice(index, 1);
  26023. }
  26024. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26025. return index;
  26026. };
  26027. /**
  26028. * Remove a skeleton for the list of scene's skeletons
  26029. * @param toRemove defines the skeleton to remove
  26030. * @returns the index where the skeleton was in the skeleton list
  26031. */
  26032. Scene.prototype.removeSkeleton = function (toRemove) {
  26033. var index = this.skeletons.indexOf(toRemove);
  26034. if (index !== -1) {
  26035. // Remove from the scene if found
  26036. this.skeletons.splice(index, 1);
  26037. }
  26038. return index;
  26039. };
  26040. /**
  26041. * Remove a morph target for the list of scene's morph targets
  26042. * @param toRemove defines the morph target to remove
  26043. * @returns the index where the morph target was in the morph target list
  26044. */
  26045. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26046. var index = this.morphTargetManagers.indexOf(toRemove);
  26047. if (index !== -1) {
  26048. // Remove from the scene if found
  26049. this.morphTargetManagers.splice(index, 1);
  26050. }
  26051. return index;
  26052. };
  26053. /**
  26054. * Remove a light for the list of scene's lights
  26055. * @param toRemove defines the light to remove
  26056. * @returns the index where the light was in the light list
  26057. */
  26058. Scene.prototype.removeLight = function (toRemove) {
  26059. var index = this.lights.indexOf(toRemove);
  26060. if (index !== -1) {
  26061. // Remove from meshes
  26062. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26063. var mesh = _a[_i];
  26064. mesh._removeLightSource(toRemove);
  26065. }
  26066. // Remove from the scene if mesh found
  26067. this.lights.splice(index, 1);
  26068. this.sortLightsByPriority();
  26069. }
  26070. this.onLightRemovedObservable.notifyObservers(toRemove);
  26071. return index;
  26072. };
  26073. /**
  26074. * Remove a camera for the list of scene's cameras
  26075. * @param toRemove defines the camera to remove
  26076. * @returns the index where the camera was in the camera list
  26077. */
  26078. Scene.prototype.removeCamera = function (toRemove) {
  26079. var index = this.cameras.indexOf(toRemove);
  26080. if (index !== -1) {
  26081. // Remove from the scene if mesh found
  26082. this.cameras.splice(index, 1);
  26083. }
  26084. // Remove from activeCameras
  26085. var index2 = this.activeCameras.indexOf(toRemove);
  26086. if (index2 !== -1) {
  26087. // Remove from the scene if mesh found
  26088. this.activeCameras.splice(index2, 1);
  26089. }
  26090. // Reset the activeCamera
  26091. if (this.activeCamera === toRemove) {
  26092. if (this.cameras.length > 0) {
  26093. this.activeCamera = this.cameras[0];
  26094. }
  26095. else {
  26096. this.activeCamera = null;
  26097. }
  26098. }
  26099. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26100. return index;
  26101. };
  26102. /**
  26103. * Remove a particle system for the list of scene's particle systems
  26104. * @param toRemove defines the particle system to remove
  26105. * @returns the index where the particle system was in the particle system list
  26106. */
  26107. Scene.prototype.removeParticleSystem = function (toRemove) {
  26108. var index = this.particleSystems.indexOf(toRemove);
  26109. if (index !== -1) {
  26110. this.particleSystems.splice(index, 1);
  26111. }
  26112. return index;
  26113. };
  26114. /**
  26115. * Remove a animation for the list of scene's animations
  26116. * @param toRemove defines the animation to remove
  26117. * @returns the index where the animation was in the animation list
  26118. */
  26119. Scene.prototype.removeAnimation = function (toRemove) {
  26120. var index = this.animations.indexOf(toRemove);
  26121. if (index !== -1) {
  26122. this.animations.splice(index, 1);
  26123. }
  26124. return index;
  26125. };
  26126. /**
  26127. * Removes the given animation group from this scene.
  26128. * @param toRemove The animation group to remove
  26129. * @returns The index of the removed animation group
  26130. */
  26131. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26132. var index = this.animationGroups.indexOf(toRemove);
  26133. if (index !== -1) {
  26134. this.animationGroups.splice(index, 1);
  26135. }
  26136. return index;
  26137. };
  26138. /**
  26139. * Removes the given multi-material from this scene.
  26140. * @param toRemove The multi-material to remove
  26141. * @returns The index of the removed multi-material
  26142. */
  26143. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26144. var index = this.multiMaterials.indexOf(toRemove);
  26145. if (index !== -1) {
  26146. this.multiMaterials.splice(index, 1);
  26147. }
  26148. return index;
  26149. };
  26150. /**
  26151. * Removes the given material from this scene.
  26152. * @param toRemove The material to remove
  26153. * @returns The index of the removed material
  26154. */
  26155. Scene.prototype.removeMaterial = function (toRemove) {
  26156. var index = this.materials.indexOf(toRemove);
  26157. if (index !== -1) {
  26158. this.materials.splice(index, 1);
  26159. }
  26160. return index;
  26161. };
  26162. /**
  26163. * Removes the given lens flare system from this scene.
  26164. * @param toRemove The lens flare system to remove
  26165. * @returns The index of the removed lens flare system
  26166. */
  26167. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26168. var index = this.lensFlareSystems.indexOf(toRemove);
  26169. if (index !== -1) {
  26170. this.lensFlareSystems.splice(index, 1);
  26171. }
  26172. return index;
  26173. };
  26174. /**
  26175. * Removes the given action manager from this scene.
  26176. * @param toRemove The action manager to remove
  26177. * @returns The index of the removed action manager
  26178. */
  26179. Scene.prototype.removeActionManager = function (toRemove) {
  26180. var index = this._actionManagers.indexOf(toRemove);
  26181. if (index !== -1) {
  26182. this._actionManagers.splice(index, 1);
  26183. }
  26184. return index;
  26185. };
  26186. /**
  26187. * Removes the given effect layer from this scene.
  26188. * @param toRemove defines the effect layer to remove
  26189. * @returns the index of the removed effect layer
  26190. */
  26191. Scene.prototype.removeEffectLayer = function (toRemove) {
  26192. var index = this.effectLayers.indexOf(toRemove);
  26193. if (index !== -1) {
  26194. this.effectLayers.splice(index, 1);
  26195. }
  26196. return index;
  26197. };
  26198. /**
  26199. * Removes the given texture from this scene.
  26200. * @param toRemove The texture to remove
  26201. * @returns The index of the removed texture
  26202. */
  26203. Scene.prototype.removeTexture = function (toRemove) {
  26204. var index = this.textures.indexOf(toRemove);
  26205. if (index !== -1) {
  26206. this.textures.splice(index, 1);
  26207. }
  26208. return index;
  26209. };
  26210. /**
  26211. * Adds the given light to this scene
  26212. * @param newLight The light to add
  26213. */
  26214. Scene.prototype.addLight = function (newLight) {
  26215. this.lights.push(newLight);
  26216. this.sortLightsByPriority();
  26217. // Add light to all meshes (To support if the light is removed and then readded)
  26218. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26219. var mesh = _a[_i];
  26220. if (mesh._lightSources.indexOf(newLight) === -1) {
  26221. mesh._lightSources.push(newLight);
  26222. mesh._resyncLightSources();
  26223. }
  26224. }
  26225. this.onNewLightAddedObservable.notifyObservers(newLight);
  26226. };
  26227. /**
  26228. * Sorts the list list based on light priorities
  26229. */
  26230. Scene.prototype.sortLightsByPriority = function () {
  26231. if (this.requireLightSorting) {
  26232. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26233. }
  26234. };
  26235. /**
  26236. * Adds the given camera to this scene
  26237. * @param newCamera The camera to add
  26238. */
  26239. Scene.prototype.addCamera = function (newCamera) {
  26240. this.cameras.push(newCamera);
  26241. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26242. };
  26243. /**
  26244. * Adds the given skeleton to this scene
  26245. * @param newSkeleton The skeleton to add
  26246. */
  26247. Scene.prototype.addSkeleton = function (newSkeleton) {
  26248. this.skeletons.push(newSkeleton);
  26249. };
  26250. /**
  26251. * Adds the given particle system to this scene
  26252. * @param newParticleSystem The particle system to add
  26253. */
  26254. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26255. this.particleSystems.push(newParticleSystem);
  26256. };
  26257. /**
  26258. * Adds the given animation to this scene
  26259. * @param newAnimation The animation to add
  26260. */
  26261. Scene.prototype.addAnimation = function (newAnimation) {
  26262. this.animations.push(newAnimation);
  26263. };
  26264. /**
  26265. * Adds the given animation group to this scene.
  26266. * @param newAnimationGroup The animation group to add
  26267. */
  26268. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26269. this.animationGroups.push(newAnimationGroup);
  26270. };
  26271. /**
  26272. * Adds the given multi-material to this scene
  26273. * @param newMultiMaterial The multi-material to add
  26274. */
  26275. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26276. this.multiMaterials.push(newMultiMaterial);
  26277. };
  26278. /**
  26279. * Adds the given material to this scene
  26280. * @param newMaterial The material to add
  26281. */
  26282. Scene.prototype.addMaterial = function (newMaterial) {
  26283. this.materials.push(newMaterial);
  26284. };
  26285. /**
  26286. * Adds the given morph target to this scene
  26287. * @param newMorphTargetManager The morph target to add
  26288. */
  26289. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26290. this.morphTargetManagers.push(newMorphTargetManager);
  26291. };
  26292. /**
  26293. * Adds the given geometry to this scene
  26294. * @param newGeometry The geometry to add
  26295. */
  26296. Scene.prototype.addGeometry = function (newGeometry) {
  26297. this._geometries.push(newGeometry);
  26298. };
  26299. /**
  26300. * Adds the given lens flare system to this scene
  26301. * @param newLensFlareSystem The lens flare system to add
  26302. */
  26303. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26304. this.lensFlareSystems.push(newLensFlareSystem);
  26305. };
  26306. /**
  26307. * Adds the given effect layer to this scene
  26308. * @param newEffectLayer defines the effect layer to add
  26309. */
  26310. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26311. this.effectLayers.push(newEffectLayer);
  26312. };
  26313. /**
  26314. * Adds the given action manager to this scene
  26315. * @param newActionManager The action manager to add
  26316. */
  26317. Scene.prototype.addActionManager = function (newActionManager) {
  26318. this._actionManagers.push(newActionManager);
  26319. };
  26320. /**
  26321. * Adds the given texture to this scene.
  26322. * @param newTexture The texture to add
  26323. */
  26324. Scene.prototype.addTexture = function (newTexture) {
  26325. this.textures.push(newTexture);
  26326. };
  26327. /**
  26328. * Switch active camera
  26329. * @param newCamera defines the new active camera
  26330. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26331. */
  26332. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26333. if (attachControl === void 0) { attachControl = true; }
  26334. var canvas = this._engine.getRenderingCanvas();
  26335. if (!canvas) {
  26336. return;
  26337. }
  26338. if (this.activeCamera) {
  26339. this.activeCamera.detachControl(canvas);
  26340. }
  26341. this.activeCamera = newCamera;
  26342. if (attachControl) {
  26343. newCamera.attachControl(canvas);
  26344. }
  26345. };
  26346. /**
  26347. * sets the active camera of the scene using its ID
  26348. * @param id defines the camera's ID
  26349. * @return the new active camera or null if none found.
  26350. */
  26351. Scene.prototype.setActiveCameraByID = function (id) {
  26352. var camera = this.getCameraByID(id);
  26353. if (camera) {
  26354. this.activeCamera = camera;
  26355. return camera;
  26356. }
  26357. return null;
  26358. };
  26359. /**
  26360. * sets the active camera of the scene using its name
  26361. * @param name defines the camera's name
  26362. * @returns the new active camera or null if none found.
  26363. */
  26364. Scene.prototype.setActiveCameraByName = function (name) {
  26365. var camera = this.getCameraByName(name);
  26366. if (camera) {
  26367. this.activeCamera = camera;
  26368. return camera;
  26369. }
  26370. return null;
  26371. };
  26372. /**
  26373. * get an animation group using its name
  26374. * @param name defines the material's name
  26375. * @return the animation group or null if none found.
  26376. */
  26377. Scene.prototype.getAnimationGroupByName = function (name) {
  26378. for (var index = 0; index < this.animationGroups.length; index++) {
  26379. if (this.animationGroups[index].name === name) {
  26380. return this.animationGroups[index];
  26381. }
  26382. }
  26383. return null;
  26384. };
  26385. /**
  26386. * get a material using its id
  26387. * @param id defines the material's ID
  26388. * @return the material or null if none found.
  26389. */
  26390. Scene.prototype.getMaterialByID = function (id) {
  26391. for (var index = 0; index < this.materials.length; index++) {
  26392. if (this.materials[index].id === id) {
  26393. return this.materials[index];
  26394. }
  26395. }
  26396. return null;
  26397. };
  26398. /**
  26399. * Gets a material using its name
  26400. * @param name defines the material's name
  26401. * @return the material or null if none found.
  26402. */
  26403. Scene.prototype.getMaterialByName = function (name) {
  26404. for (var index = 0; index < this.materials.length; index++) {
  26405. if (this.materials[index].name === name) {
  26406. return this.materials[index];
  26407. }
  26408. }
  26409. return null;
  26410. };
  26411. /**
  26412. * Gets a lens flare system using its name
  26413. * @param name defines the name to look for
  26414. * @returns the lens flare system or null if not found
  26415. */
  26416. Scene.prototype.getLensFlareSystemByName = function (name) {
  26417. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26418. if (this.lensFlareSystems[index].name === name) {
  26419. return this.lensFlareSystems[index];
  26420. }
  26421. }
  26422. return null;
  26423. };
  26424. /**
  26425. * Gets a lens flare system using its id
  26426. * @param id defines the id to look for
  26427. * @returns the lens flare system or null if not found
  26428. */
  26429. Scene.prototype.getLensFlareSystemByID = function (id) {
  26430. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26431. if (this.lensFlareSystems[index].id === id) {
  26432. return this.lensFlareSystems[index];
  26433. }
  26434. }
  26435. return null;
  26436. };
  26437. /**
  26438. * Gets a camera using its id
  26439. * @param id defines the id to look for
  26440. * @returns the camera or null if not found
  26441. */
  26442. Scene.prototype.getCameraByID = function (id) {
  26443. for (var index = 0; index < this.cameras.length; index++) {
  26444. if (this.cameras[index].id === id) {
  26445. return this.cameras[index];
  26446. }
  26447. }
  26448. return null;
  26449. };
  26450. /**
  26451. * Gets a camera using its unique id
  26452. * @param uniqueId defines the unique id to look for
  26453. * @returns the camera or null if not found
  26454. */
  26455. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26456. for (var index = 0; index < this.cameras.length; index++) {
  26457. if (this.cameras[index].uniqueId === uniqueId) {
  26458. return this.cameras[index];
  26459. }
  26460. }
  26461. return null;
  26462. };
  26463. /**
  26464. * Gets a camera using its name
  26465. * @param name defines the camera's name
  26466. * @return the camera or null if none found.
  26467. */
  26468. Scene.prototype.getCameraByName = function (name) {
  26469. for (var index = 0; index < this.cameras.length; index++) {
  26470. if (this.cameras[index].name === name) {
  26471. return this.cameras[index];
  26472. }
  26473. }
  26474. return null;
  26475. };
  26476. /**
  26477. * Gets a bone using its id
  26478. * @param id defines the bone's id
  26479. * @return the bone or null if not found
  26480. */
  26481. Scene.prototype.getBoneByID = function (id) {
  26482. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26483. var skeleton = this.skeletons[skeletonIndex];
  26484. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26485. if (skeleton.bones[boneIndex].id === id) {
  26486. return skeleton.bones[boneIndex];
  26487. }
  26488. }
  26489. }
  26490. return null;
  26491. };
  26492. /**
  26493. * Gets a bone using its id
  26494. * @param name defines the bone's name
  26495. * @return the bone or null if not found
  26496. */
  26497. Scene.prototype.getBoneByName = function (name) {
  26498. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26499. var skeleton = this.skeletons[skeletonIndex];
  26500. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26501. if (skeleton.bones[boneIndex].name === name) {
  26502. return skeleton.bones[boneIndex];
  26503. }
  26504. }
  26505. }
  26506. return null;
  26507. };
  26508. /**
  26509. * Gets a light node using its name
  26510. * @param name defines the the light's name
  26511. * @return the light or null if none found.
  26512. */
  26513. Scene.prototype.getLightByName = function (name) {
  26514. for (var index = 0; index < this.lights.length; index++) {
  26515. if (this.lights[index].name === name) {
  26516. return this.lights[index];
  26517. }
  26518. }
  26519. return null;
  26520. };
  26521. /**
  26522. * Gets a light node using its id
  26523. * @param id defines the light's id
  26524. * @return the light or null if none found.
  26525. */
  26526. Scene.prototype.getLightByID = function (id) {
  26527. for (var index = 0; index < this.lights.length; index++) {
  26528. if (this.lights[index].id === id) {
  26529. return this.lights[index];
  26530. }
  26531. }
  26532. return null;
  26533. };
  26534. /**
  26535. * Gets a light node using its scene-generated unique ID
  26536. * @param uniqueId defines the light's unique id
  26537. * @return the light or null if none found.
  26538. */
  26539. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26540. for (var index = 0; index < this.lights.length; index++) {
  26541. if (this.lights[index].uniqueId === uniqueId) {
  26542. return this.lights[index];
  26543. }
  26544. }
  26545. return null;
  26546. };
  26547. /**
  26548. * Gets a particle system by id
  26549. * @param id defines the particle system id
  26550. * @return the corresponding system or null if none found
  26551. */
  26552. Scene.prototype.getParticleSystemByID = function (id) {
  26553. for (var index = 0; index < this.particleSystems.length; index++) {
  26554. if (this.particleSystems[index].id === id) {
  26555. return this.particleSystems[index];
  26556. }
  26557. }
  26558. return null;
  26559. };
  26560. /**
  26561. * Gets a geometry using its ID
  26562. * @param id defines the geometry's id
  26563. * @return the geometry or null if none found.
  26564. */
  26565. Scene.prototype.getGeometryByID = function (id) {
  26566. for (var index = 0; index < this._geometries.length; index++) {
  26567. if (this._geometries[index].id === id) {
  26568. return this._geometries[index];
  26569. }
  26570. }
  26571. return null;
  26572. };
  26573. /**
  26574. * Add a new geometry to this scene
  26575. * @param geometry defines the geometry to be added to the scene.
  26576. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26577. * @return a boolean defining if the geometry was added or not
  26578. */
  26579. Scene.prototype.pushGeometry = function (geometry, force) {
  26580. if (!force && this.getGeometryByID(geometry.id)) {
  26581. return false;
  26582. }
  26583. this._geometries.push(geometry);
  26584. //notify the collision coordinator
  26585. if (this.collisionCoordinator) {
  26586. this.collisionCoordinator.onGeometryAdded(geometry);
  26587. }
  26588. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26589. return true;
  26590. };
  26591. /**
  26592. * Removes an existing geometry
  26593. * @param geometry defines the geometry to be removed from the scene
  26594. * @return a boolean defining if the geometry was removed or not
  26595. */
  26596. Scene.prototype.removeGeometry = function (geometry) {
  26597. var index = this._geometries.indexOf(geometry);
  26598. if (index > -1) {
  26599. this._geometries.splice(index, 1);
  26600. //notify the collision coordinator
  26601. if (this.collisionCoordinator) {
  26602. this.collisionCoordinator.onGeometryDeleted(geometry);
  26603. }
  26604. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26605. return true;
  26606. }
  26607. return false;
  26608. };
  26609. /**
  26610. * Gets the list of geometries attached to the scene
  26611. * @returns an array of Geometry
  26612. */
  26613. Scene.prototype.getGeometries = function () {
  26614. return this._geometries;
  26615. };
  26616. /**
  26617. * Gets the first added mesh found of a given ID
  26618. * @param id defines the id to search for
  26619. * @return the mesh found or null if not found at all
  26620. */
  26621. Scene.prototype.getMeshByID = function (id) {
  26622. for (var index = 0; index < this.meshes.length; index++) {
  26623. if (this.meshes[index].id === id) {
  26624. return this.meshes[index];
  26625. }
  26626. }
  26627. return null;
  26628. };
  26629. /**
  26630. * Gets a list of meshes using their id
  26631. * @param id defines the id to search for
  26632. * @returns a list of meshes
  26633. */
  26634. Scene.prototype.getMeshesByID = function (id) {
  26635. return this.meshes.filter(function (m) {
  26636. return m.id === id;
  26637. });
  26638. };
  26639. /**
  26640. * Gets the first added transform node found of a given ID
  26641. * @param id defines the id to search for
  26642. * @return the found transform node or null if not found at all.
  26643. */
  26644. Scene.prototype.getTransformNodeByID = function (id) {
  26645. for (var index = 0; index < this.transformNodes.length; index++) {
  26646. if (this.transformNodes[index].id === id) {
  26647. return this.transformNodes[index];
  26648. }
  26649. }
  26650. return null;
  26651. };
  26652. /**
  26653. * Gets a list of transform nodes using their id
  26654. * @param id defines the id to search for
  26655. * @returns a list of transform nodes
  26656. */
  26657. Scene.prototype.getTransformNodesByID = function (id) {
  26658. return this.transformNodes.filter(function (m) {
  26659. return m.id === id;
  26660. });
  26661. };
  26662. /**
  26663. * Gets a mesh with its auto-generated unique id
  26664. * @param uniqueId defines the unique id to search for
  26665. * @return the found mesh or null if not found at all.
  26666. */
  26667. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26668. for (var index = 0; index < this.meshes.length; index++) {
  26669. if (this.meshes[index].uniqueId === uniqueId) {
  26670. return this.meshes[index];
  26671. }
  26672. }
  26673. return null;
  26674. };
  26675. /**
  26676. * Gets a the last added mesh using a given id
  26677. * @param id defines the id to search for
  26678. * @return the found mesh or null if not found at all.
  26679. */
  26680. Scene.prototype.getLastMeshByID = function (id) {
  26681. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26682. if (this.meshes[index].id === id) {
  26683. return this.meshes[index];
  26684. }
  26685. }
  26686. return null;
  26687. };
  26688. /**
  26689. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26690. * @param id defines the id to search for
  26691. * @return the found node or null if not found at all
  26692. */
  26693. Scene.prototype.getLastEntryByID = function (id) {
  26694. var index;
  26695. for (index = this.meshes.length - 1; index >= 0; index--) {
  26696. if (this.meshes[index].id === id) {
  26697. return this.meshes[index];
  26698. }
  26699. }
  26700. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26701. if (this.transformNodes[index].id === id) {
  26702. return this.transformNodes[index];
  26703. }
  26704. }
  26705. for (index = this.cameras.length - 1; index >= 0; index--) {
  26706. if (this.cameras[index].id === id) {
  26707. return this.cameras[index];
  26708. }
  26709. }
  26710. for (index = this.lights.length - 1; index >= 0; index--) {
  26711. if (this.lights[index].id === id) {
  26712. return this.lights[index];
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * Gets a node (Mesh, Camera, Light) using a given id
  26719. * @param id defines the id to search for
  26720. * @return the found node or null if not found at all
  26721. */
  26722. Scene.prototype.getNodeByID = function (id) {
  26723. var mesh = this.getMeshByID(id);
  26724. if (mesh) {
  26725. return mesh;
  26726. }
  26727. var light = this.getLightByID(id);
  26728. if (light) {
  26729. return light;
  26730. }
  26731. var camera = this.getCameraByID(id);
  26732. if (camera) {
  26733. return camera;
  26734. }
  26735. var bone = this.getBoneByID(id);
  26736. return bone;
  26737. };
  26738. /**
  26739. * Gets a node (Mesh, Camera, Light) using a given name
  26740. * @param name defines the name to search for
  26741. * @return the found node or null if not found at all.
  26742. */
  26743. Scene.prototype.getNodeByName = function (name) {
  26744. var mesh = this.getMeshByName(name);
  26745. if (mesh) {
  26746. return mesh;
  26747. }
  26748. var light = this.getLightByName(name);
  26749. if (light) {
  26750. return light;
  26751. }
  26752. var camera = this.getCameraByName(name);
  26753. if (camera) {
  26754. return camera;
  26755. }
  26756. var bone = this.getBoneByName(name);
  26757. return bone;
  26758. };
  26759. /**
  26760. * Gets a mesh using a given name
  26761. * @param name defines the name to search for
  26762. * @return the found mesh or null if not found at all.
  26763. */
  26764. Scene.prototype.getMeshByName = function (name) {
  26765. for (var index = 0; index < this.meshes.length; index++) {
  26766. if (this.meshes[index].name === name) {
  26767. return this.meshes[index];
  26768. }
  26769. }
  26770. return null;
  26771. };
  26772. /**
  26773. * Gets a transform node using a given name
  26774. * @param name defines the name to search for
  26775. * @return the found transform node or null if not found at all.
  26776. */
  26777. Scene.prototype.getTransformNodeByName = function (name) {
  26778. for (var index = 0; index < this.transformNodes.length; index++) {
  26779. if (this.transformNodes[index].name === name) {
  26780. return this.transformNodes[index];
  26781. }
  26782. }
  26783. return null;
  26784. };
  26785. /**
  26786. * Gets a sound using a given name
  26787. * @param name defines the name to search for
  26788. * @return the found sound or null if not found at all.
  26789. */
  26790. Scene.prototype.getSoundByName = function (name) {
  26791. var index;
  26792. if (BABYLON.AudioEngine) {
  26793. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26794. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26795. return this.mainSoundTrack.soundCollection[index];
  26796. }
  26797. }
  26798. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26799. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26800. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26801. return this.soundTracks[sdIndex].soundCollection[index];
  26802. }
  26803. }
  26804. }
  26805. }
  26806. return null;
  26807. };
  26808. /**
  26809. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26810. * @param id defines the id to search for
  26811. * @return the found skeleton or null if not found at all.
  26812. */
  26813. Scene.prototype.getLastSkeletonByID = function (id) {
  26814. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26815. if (this.skeletons[index].id === id) {
  26816. return this.skeletons[index];
  26817. }
  26818. }
  26819. return null;
  26820. };
  26821. /**
  26822. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26823. * @param id defines the id to search for
  26824. * @return the found skeleton or null if not found at all.
  26825. */
  26826. Scene.prototype.getSkeletonById = function (id) {
  26827. for (var index = 0; index < this.skeletons.length; index++) {
  26828. if (this.skeletons[index].id === id) {
  26829. return this.skeletons[index];
  26830. }
  26831. }
  26832. return null;
  26833. };
  26834. /**
  26835. * Gets a skeleton using a given name
  26836. * @param name defines the name to search for
  26837. * @return the found skeleton or null if not found at all.
  26838. */
  26839. Scene.prototype.getSkeletonByName = function (name) {
  26840. for (var index = 0; index < this.skeletons.length; index++) {
  26841. if (this.skeletons[index].name === name) {
  26842. return this.skeletons[index];
  26843. }
  26844. }
  26845. return null;
  26846. };
  26847. /**
  26848. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26849. * @param id defines the id to search for
  26850. * @return the found morph target manager or null if not found at all.
  26851. */
  26852. Scene.prototype.getMorphTargetManagerById = function (id) {
  26853. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26854. if (this.morphTargetManagers[index].uniqueId === id) {
  26855. return this.morphTargetManagers[index];
  26856. }
  26857. }
  26858. return null;
  26859. };
  26860. /**
  26861. * Gets a boolean indicating if the given mesh is active
  26862. * @param mesh defines the mesh to look for
  26863. * @returns true if the mesh is in the active list
  26864. */
  26865. Scene.prototype.isActiveMesh = function (mesh) {
  26866. return (this._activeMeshes.indexOf(mesh) !== -1);
  26867. };
  26868. /**
  26869. * Return a the first highlight layer of the scene with a given name.
  26870. * @param name The name of the highlight layer to look for.
  26871. * @return The highlight layer if found otherwise null.
  26872. */
  26873. Scene.prototype.getHighlightLayerByName = function (name) {
  26874. for (var index = 0; index < this.effectLayers.length; index++) {
  26875. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26876. return this.effectLayers[index];
  26877. }
  26878. }
  26879. return null;
  26880. };
  26881. /**
  26882. * Return a the first highlight layer of the scene with a given name.
  26883. * @param name The name of the highlight layer to look for.
  26884. * @return The highlight layer if found otherwise null.
  26885. */
  26886. Scene.prototype.getGlowLayerByName = function (name) {
  26887. for (var index = 0; index < this.effectLayers.length; index++) {
  26888. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26889. return this.effectLayers[index];
  26890. }
  26891. }
  26892. return null;
  26893. };
  26894. Object.defineProperty(Scene.prototype, "uid", {
  26895. /**
  26896. * Return a unique id as a string which can serve as an identifier for the scene
  26897. */
  26898. get: function () {
  26899. if (!this._uid) {
  26900. this._uid = BABYLON.Tools.RandomId();
  26901. }
  26902. return this._uid;
  26903. },
  26904. enumerable: true,
  26905. configurable: true
  26906. });
  26907. /**
  26908. * Add an externaly attached data from its key.
  26909. * This method call will fail and return false, if such key already exists.
  26910. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26911. * @param key the unique key that identifies the data
  26912. * @param data the data object to associate to the key for this Engine instance
  26913. * @return true if no such key were already present and the data was added successfully, false otherwise
  26914. */
  26915. Scene.prototype.addExternalData = function (key, data) {
  26916. if (!this._externalData) {
  26917. this._externalData = new BABYLON.StringDictionary();
  26918. }
  26919. return this._externalData.add(key, data);
  26920. };
  26921. /**
  26922. * Get an externaly attached data from its key
  26923. * @param key the unique key that identifies the data
  26924. * @return the associated data, if present (can be null), or undefined if not present
  26925. */
  26926. Scene.prototype.getExternalData = function (key) {
  26927. if (!this._externalData) {
  26928. return null;
  26929. }
  26930. return this._externalData.get(key);
  26931. };
  26932. /**
  26933. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26934. * @param key the unique key that identifies the data
  26935. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26936. * @return the associated data, can be null if the factory returned null.
  26937. */
  26938. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26939. if (!this._externalData) {
  26940. this._externalData = new BABYLON.StringDictionary();
  26941. }
  26942. return this._externalData.getOrAddWithFactory(key, factory);
  26943. };
  26944. /**
  26945. * Remove an externaly attached data from the Engine instance
  26946. * @param key the unique key that identifies the data
  26947. * @return true if the data was successfully removed, false if it doesn't exist
  26948. */
  26949. Scene.prototype.removeExternalData = function (key) {
  26950. return this._externalData.remove(key);
  26951. };
  26952. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26953. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26954. if (mesh.showSubMeshesBoundingBox) {
  26955. var boundingInfo = subMesh.getBoundingInfo();
  26956. if (boundingInfo !== null && boundingInfo !== undefined) {
  26957. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26958. }
  26959. }
  26960. var material = subMesh.getMaterial();
  26961. if (material !== null && material !== undefined) {
  26962. // Render targets
  26963. if (material.getRenderTargetTextures !== undefined) {
  26964. if (this._processedMaterials.indexOf(material) === -1) {
  26965. this._processedMaterials.push(material);
  26966. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26967. }
  26968. }
  26969. // Dispatch
  26970. this._activeIndices.addCount(subMesh.indexCount, false);
  26971. this._renderingManager.dispatch(subMesh, mesh, material);
  26972. }
  26973. }
  26974. };
  26975. /**
  26976. * Clear the processed materials smart array preventing retention point in material dispose.
  26977. */
  26978. Scene.prototype.freeProcessedMaterials = function () {
  26979. this._processedMaterials.dispose();
  26980. };
  26981. /**
  26982. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26983. */
  26984. Scene.prototype.freeActiveMeshes = function () {
  26985. this._activeMeshes.dispose();
  26986. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26987. this.activeCamera._activeMeshes.dispose();
  26988. }
  26989. if (this.activeCameras) {
  26990. for (var i = 0; i < this.activeCameras.length; i++) {
  26991. var activeCamera = this.activeCameras[i];
  26992. if (activeCamera && activeCamera._activeMeshes) {
  26993. activeCamera._activeMeshes.dispose();
  26994. }
  26995. }
  26996. }
  26997. };
  26998. /**
  26999. * Clear the info related to rendering groups preventing retention points during dispose.
  27000. */
  27001. Scene.prototype.freeRenderingGroups = function () {
  27002. if (this._renderingManager) {
  27003. this._renderingManager.freeRenderingGroups();
  27004. }
  27005. if (this.textures) {
  27006. for (var i = 0; i < this.textures.length; i++) {
  27007. var texture = this.textures[i];
  27008. if (texture && texture.renderList) {
  27009. texture.freeRenderingGroups();
  27010. }
  27011. }
  27012. }
  27013. };
  27014. /** @hidden */
  27015. Scene.prototype._isInIntermediateRendering = function () {
  27016. return this._intermediateRendering;
  27017. };
  27018. /**
  27019. * Defines the current active mesh candidate provider
  27020. * @param provider defines the provider to use
  27021. */
  27022. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27023. this._activeMeshCandidateProvider = provider;
  27024. };
  27025. /**
  27026. * Gets the current active mesh candidate provider
  27027. * @returns the current active mesh candidate provider
  27028. */
  27029. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27030. return this._activeMeshCandidateProvider;
  27031. };
  27032. /**
  27033. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27034. * @returns the current scene
  27035. */
  27036. Scene.prototype.freezeActiveMeshes = function () {
  27037. if (!this.activeCamera) {
  27038. return this;
  27039. }
  27040. if (!this._frustumPlanes) {
  27041. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27042. }
  27043. this._evaluateActiveMeshes();
  27044. this._activeMeshesFrozen = true;
  27045. return this;
  27046. };
  27047. /**
  27048. * Use this function to restart evaluating active meshes on every frame
  27049. * @returns the current scene
  27050. */
  27051. Scene.prototype.unfreezeActiveMeshes = function () {
  27052. this._activeMeshesFrozen = false;
  27053. return this;
  27054. };
  27055. Scene.prototype._evaluateActiveMeshes = function () {
  27056. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27057. return;
  27058. }
  27059. if (!this.activeCamera) {
  27060. return;
  27061. }
  27062. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27063. this.activeCamera._activeMeshes.reset();
  27064. this._activeMeshes.reset();
  27065. this._renderingManager.reset();
  27066. this._processedMaterials.reset();
  27067. this._activeParticleSystems.reset();
  27068. this._activeSkeletons.reset();
  27069. this._softwareSkinnedMeshes.reset();
  27070. if (this._boundingBoxRenderer) {
  27071. this._boundingBoxRenderer.reset();
  27072. }
  27073. // Meshes
  27074. var meshes;
  27075. var len;
  27076. var checkIsEnabled = true;
  27077. // Determine mesh candidates
  27078. if (this._activeMeshCandidateProvider !== undefined) {
  27079. // Use _activeMeshCandidateProvider
  27080. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27081. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27082. if (meshes !== undefined) {
  27083. len = meshes.length;
  27084. }
  27085. else {
  27086. len = 0;
  27087. }
  27088. }
  27089. else if (this._selectionOctree !== undefined) {
  27090. // Octree
  27091. var selection = this._selectionOctree.select(this._frustumPlanes);
  27092. meshes = selection.data;
  27093. len = selection.length;
  27094. }
  27095. else {
  27096. // Full scene traversal
  27097. len = this.meshes.length;
  27098. meshes = this.meshes;
  27099. }
  27100. // Check each mesh
  27101. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27102. mesh = meshes[meshIndex];
  27103. if (mesh.isBlocked) {
  27104. continue;
  27105. }
  27106. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27107. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27108. continue;
  27109. }
  27110. mesh.computeWorldMatrix();
  27111. // Intersections
  27112. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27113. this._meshesForIntersections.pushNoDuplicate(mesh);
  27114. }
  27115. // Switch to current LOD
  27116. meshLOD = mesh.getLOD(this.activeCamera);
  27117. if (meshLOD === undefined || meshLOD === null) {
  27118. continue;
  27119. }
  27120. mesh._preActivate();
  27121. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27122. this._activeMeshes.push(mesh);
  27123. this.activeCamera._activeMeshes.push(mesh);
  27124. mesh._activate(this._renderId);
  27125. if (meshLOD !== mesh) {
  27126. meshLOD._activate(this._renderId);
  27127. }
  27128. this._activeMesh(mesh, meshLOD);
  27129. }
  27130. }
  27131. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27132. // Particle systems
  27133. if (this.particlesEnabled) {
  27134. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27135. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27136. var particleSystem = this.particleSystems[particleIndex];
  27137. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27138. continue;
  27139. }
  27140. var emitter = particleSystem.emitter;
  27141. if (!emitter.position || emitter.isEnabled()) {
  27142. this._activeParticleSystems.push(particleSystem);
  27143. particleSystem.animate();
  27144. this._renderingManager.dispatchParticles(particleSystem);
  27145. }
  27146. }
  27147. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27148. }
  27149. };
  27150. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27151. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27152. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27153. mesh.skeleton.prepare();
  27154. }
  27155. if (!mesh.computeBonesUsingShaders) {
  27156. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27157. }
  27158. }
  27159. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27160. var boundingInfo = sourceMesh.getBoundingInfo();
  27161. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27162. }
  27163. if (mesh !== undefined && mesh !== null
  27164. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27165. // Submeshes Octrees
  27166. var len;
  27167. var subMeshes;
  27168. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27169. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27170. len = intersections.length;
  27171. subMeshes = intersections.data;
  27172. }
  27173. else {
  27174. subMeshes = mesh.subMeshes;
  27175. len = subMeshes.length;
  27176. }
  27177. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27178. subMesh = subMeshes[subIndex];
  27179. this._evaluateSubMesh(subMesh, mesh);
  27180. }
  27181. }
  27182. };
  27183. /**
  27184. * Update the transform matrix to update from the current active camera
  27185. * @param force defines a boolean used to force the update even if cache is up to date
  27186. */
  27187. Scene.prototype.updateTransformMatrix = function (force) {
  27188. if (!this.activeCamera) {
  27189. return;
  27190. }
  27191. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27192. };
  27193. /**
  27194. * 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)
  27195. * @param alternateCamera defines the camera to use
  27196. */
  27197. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27198. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27199. };
  27200. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27201. if (camera && camera._skipRendering) {
  27202. return;
  27203. }
  27204. var engine = this._engine;
  27205. this.activeCamera = camera;
  27206. if (!this.activeCamera)
  27207. throw new Error("Active camera not set");
  27208. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27209. // Viewport
  27210. engine.setViewport(this.activeCamera.viewport);
  27211. // Camera
  27212. this.resetCachedMaterial();
  27213. this._renderId++;
  27214. this.updateTransformMatrix();
  27215. if (camera._alternateCamera) {
  27216. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27217. this._alternateRendering = true;
  27218. }
  27219. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27220. // Meshes
  27221. this._evaluateActiveMeshes();
  27222. // Software skinning
  27223. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27224. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27225. mesh.applySkeleton(mesh.skeleton);
  27226. }
  27227. // Render targets
  27228. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27229. var needsRestoreFrameBuffer = false;
  27230. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27231. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27232. }
  27233. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27234. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27235. }
  27236. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27237. this._intermediateRendering = true;
  27238. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27239. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27240. var renderTarget = this._renderTargets.data[renderIndex];
  27241. if (renderTarget._shouldRender()) {
  27242. this._renderId++;
  27243. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27244. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27245. }
  27246. }
  27247. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27248. this._intermediateRendering = false;
  27249. this._renderId++;
  27250. needsRestoreFrameBuffer = true; // Restore back buffer
  27251. }
  27252. // Render EffecttLayer Texture
  27253. var stencilState = this._engine.getStencilBuffer();
  27254. var renderEffects = false;
  27255. var needStencil = false;
  27256. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27257. this._intermediateRendering = true;
  27258. for (var i = 0; i < this.effectLayers.length; i++) {
  27259. var effectLayer = this.effectLayers[i];
  27260. if (effectLayer.shouldRender() &&
  27261. (!effectLayer.camera ||
  27262. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27263. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27264. renderEffects = true;
  27265. needStencil = needStencil || effectLayer.needStencil();
  27266. var renderTarget = effectLayer._mainTexture;
  27267. if (renderTarget._shouldRender()) {
  27268. this._renderId++;
  27269. renderTarget.render(false, false);
  27270. needsRestoreFrameBuffer = true;
  27271. }
  27272. }
  27273. }
  27274. this._intermediateRendering = false;
  27275. this._renderId++;
  27276. }
  27277. if (needsRestoreFrameBuffer) {
  27278. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27279. }
  27280. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27281. // Prepare Frame
  27282. this.postProcessManager._prepareFrame();
  27283. // Backgrounds
  27284. var layerIndex;
  27285. var layer;
  27286. if (this.layers.length) {
  27287. engine.setDepthBuffer(false);
  27288. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27289. layer = this.layers[layerIndex];
  27290. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27291. layer.render();
  27292. }
  27293. }
  27294. engine.setDepthBuffer(true);
  27295. }
  27296. // Activate effect Layer stencil
  27297. if (needStencil) {
  27298. this._engine.setStencilBuffer(true);
  27299. }
  27300. // Render
  27301. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27302. this._renderingManager.render(null, null, true, true);
  27303. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27304. // Restore effect Layer stencil
  27305. if (needStencil) {
  27306. this._engine.setStencilBuffer(stencilState);
  27307. }
  27308. // Bounding boxes
  27309. if (this._boundingBoxRenderer) {
  27310. this._boundingBoxRenderer.render();
  27311. }
  27312. // Lens flares
  27313. if (this.lensFlaresEnabled) {
  27314. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27315. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27316. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27317. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27318. lensFlareSystem.render();
  27319. }
  27320. }
  27321. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27322. }
  27323. // Effect Layer
  27324. if (renderEffects) {
  27325. engine.setDepthBuffer(false);
  27326. for (var i = 0; i < this.effectLayers.length; i++) {
  27327. if (this.effectLayers[i].shouldRender()) {
  27328. this.effectLayers[i].render();
  27329. }
  27330. }
  27331. engine.setDepthBuffer(true);
  27332. }
  27333. // Foregrounds
  27334. if (this.layers.length) {
  27335. engine.setDepthBuffer(false);
  27336. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27337. layer = this.layers[layerIndex];
  27338. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27339. layer.render();
  27340. }
  27341. }
  27342. engine.setDepthBuffer(true);
  27343. }
  27344. // Finalize frame
  27345. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27346. // Reset some special arrays
  27347. this._renderTargets.reset();
  27348. this._alternateRendering = false;
  27349. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27350. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27351. };
  27352. Scene.prototype._processSubCameras = function (camera) {
  27353. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27354. this._renderForCamera(camera);
  27355. return;
  27356. }
  27357. // rig cameras
  27358. for (var index = 0; index < camera._rigCameras.length; index++) {
  27359. this._renderForCamera(camera._rigCameras[index], camera);
  27360. }
  27361. this.activeCamera = camera;
  27362. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27363. };
  27364. Scene.prototype._checkIntersections = function () {
  27365. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27366. var sourceMesh = this._meshesForIntersections.data[index];
  27367. if (!sourceMesh.actionManager) {
  27368. continue;
  27369. }
  27370. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27371. var action = sourceMesh.actionManager.actions[actionIndex];
  27372. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27373. var parameters = action.getTriggerParameter();
  27374. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27375. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27376. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27377. if (areIntersecting && currentIntersectionInProgress === -1) {
  27378. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27379. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27380. sourceMesh._intersectionsInProgress.push(otherMesh);
  27381. }
  27382. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27383. sourceMesh._intersectionsInProgress.push(otherMesh);
  27384. }
  27385. }
  27386. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27387. //They intersected, and now they don't.
  27388. //is this trigger an exit trigger? execute an event.
  27389. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27390. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27391. }
  27392. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27393. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27394. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27395. return otherMesh === parameterMesh;
  27396. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27397. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27398. }
  27399. }
  27400. }
  27401. }
  27402. }
  27403. };
  27404. /**
  27405. * Render the scene
  27406. */
  27407. Scene.prototype.render = function () {
  27408. if (this.isDisposed) {
  27409. return;
  27410. }
  27411. this._activeParticles.fetchNewFrame();
  27412. this._totalVertices.fetchNewFrame();
  27413. this._activeIndices.fetchNewFrame();
  27414. this._activeBones.fetchNewFrame();
  27415. this._meshesForIntersections.reset();
  27416. this.resetCachedMaterial();
  27417. this.onBeforeAnimationsObservable.notifyObservers(this);
  27418. // Actions
  27419. if (this.actionManager) {
  27420. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27421. }
  27422. //Simplification Queue
  27423. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27424. this.simplificationQueue.executeNext();
  27425. }
  27426. if (this._engine.isDeterministicLockStep()) {
  27427. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27428. var defaultFPS = (60.0 / 1000.0);
  27429. var defaultFrameTime = 1000 / 60; // frame time in MS
  27430. if (this._physicsEngine) {
  27431. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27432. }
  27433. var stepsTaken = 0;
  27434. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27435. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27436. internalSteps = Math.min(internalSteps, maxSubSteps);
  27437. do {
  27438. this.onBeforeStepObservable.notifyObservers(this);
  27439. // Animations
  27440. this._animationRatio = defaultFrameTime * defaultFPS;
  27441. this._animate();
  27442. this.onAfterAnimationsObservable.notifyObservers(this);
  27443. // Physics
  27444. if (this._physicsEngine) {
  27445. this.onBeforePhysicsObservable.notifyObservers(this);
  27446. this._physicsEngine._step(defaultFrameTime / 1000);
  27447. this.onAfterPhysicsObservable.notifyObservers(this);
  27448. }
  27449. this.onAfterStepObservable.notifyObservers(this);
  27450. this._currentStepId++;
  27451. stepsTaken++;
  27452. deltaTime -= defaultFrameTime;
  27453. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27454. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27455. }
  27456. else {
  27457. // Animations
  27458. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27459. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27460. this._animate();
  27461. this.onAfterAnimationsObservable.notifyObservers(this);
  27462. // Physics
  27463. if (this._physicsEngine) {
  27464. this.onBeforePhysicsObservable.notifyObservers(this);
  27465. this._physicsEngine._step(deltaTime / 1000.0);
  27466. this.onAfterPhysicsObservable.notifyObservers(this);
  27467. }
  27468. }
  27469. // update gamepad manager
  27470. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27471. this._gamepadManager._checkGamepadsStatus();
  27472. }
  27473. // Update Cameras
  27474. if (this.activeCameras.length > 0) {
  27475. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27476. var camera = this.activeCameras[cameraIndex];
  27477. camera.update();
  27478. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27479. // rig cameras
  27480. for (var index = 0; index < camera._rigCameras.length; index++) {
  27481. camera._rigCameras[index].update();
  27482. }
  27483. }
  27484. }
  27485. }
  27486. else if (this.activeCamera) {
  27487. this.activeCamera.update();
  27488. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27489. // rig cameras
  27490. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27491. this.activeCamera._rigCameras[index].update();
  27492. }
  27493. }
  27494. }
  27495. // Before render
  27496. this.onBeforeRenderObservable.notifyObservers(this);
  27497. // Customs render targets
  27498. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27499. var engine = this.getEngine();
  27500. var currentActiveCamera = this.activeCamera;
  27501. if (this.renderTargetsEnabled) {
  27502. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27503. this._intermediateRendering = true;
  27504. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27505. var renderTarget = this.customRenderTargets[customIndex];
  27506. if (renderTarget._shouldRender()) {
  27507. this._renderId++;
  27508. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27509. if (!this.activeCamera)
  27510. throw new Error("Active camera not set");
  27511. // Viewport
  27512. engine.setViewport(this.activeCamera.viewport);
  27513. // Camera
  27514. this.updateTransformMatrix();
  27515. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27516. }
  27517. }
  27518. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27519. this._intermediateRendering = false;
  27520. this._renderId++;
  27521. }
  27522. // Restore back buffer
  27523. if (this.customRenderTargets.length > 0) {
  27524. engine.restoreDefaultFramebuffer();
  27525. }
  27526. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27527. this.activeCamera = currentActiveCamera;
  27528. // Procedural textures
  27529. if (this.proceduralTexturesEnabled) {
  27530. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27531. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27532. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27533. if (proceduralTexture._shouldRender()) {
  27534. proceduralTexture.render();
  27535. }
  27536. }
  27537. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27538. }
  27539. // Clear
  27540. if (this.autoClearDepthAndStencil || this.autoClear) {
  27541. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27542. }
  27543. // Shadows
  27544. if (this.shadowsEnabled) {
  27545. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27546. var light = this.lights[lightIndex];
  27547. var shadowGenerator = light.getShadowGenerator();
  27548. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27549. var shadowMap = (shadowGenerator.getShadowMap());
  27550. if (this.textures.indexOf(shadowMap) !== -1) {
  27551. this._renderTargets.push(shadowMap);
  27552. }
  27553. }
  27554. }
  27555. }
  27556. // Depth renderer
  27557. for (var key in this._depthRenderer) {
  27558. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27559. }
  27560. // Geometry renderer
  27561. if (this._geometryBufferRenderer) {
  27562. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27563. }
  27564. // RenderPipeline
  27565. if (this._postProcessRenderPipelineManager) {
  27566. this._postProcessRenderPipelineManager.update();
  27567. }
  27568. // Multi-cameras?
  27569. if (this.activeCameras.length > 0) {
  27570. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27571. if (cameraIndex > 0) {
  27572. this._engine.clear(null, false, true, true);
  27573. }
  27574. this._processSubCameras(this.activeCameras[cameraIndex]);
  27575. }
  27576. }
  27577. else {
  27578. if (!this.activeCamera) {
  27579. throw new Error("No camera defined");
  27580. }
  27581. this._processSubCameras(this.activeCamera);
  27582. }
  27583. // Intersection checks
  27584. this._checkIntersections();
  27585. // Update the audio listener attached to the camera
  27586. if (BABYLON.AudioEngine) {
  27587. this._updateAudioParameters();
  27588. }
  27589. // After render
  27590. if (this.afterRender) {
  27591. this.afterRender();
  27592. }
  27593. this.onAfterRenderObservable.notifyObservers(this);
  27594. // Cleaning
  27595. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27596. var data = this._toBeDisposed.data[index];
  27597. if (data) {
  27598. data.dispose();
  27599. }
  27600. this._toBeDisposed[index] = null;
  27601. }
  27602. this._toBeDisposed.reset();
  27603. if (this.dumpNextRenderTargets) {
  27604. this.dumpNextRenderTargets = false;
  27605. }
  27606. this._activeBones.addCount(0, true);
  27607. this._activeIndices.addCount(0, true);
  27608. this._activeParticles.addCount(0, true);
  27609. };
  27610. Scene.prototype._updateAudioParameters = function () {
  27611. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27612. return;
  27613. }
  27614. var listeningCamera;
  27615. var audioEngine = BABYLON.Engine.audioEngine;
  27616. if (this.activeCameras.length > 0) {
  27617. listeningCamera = this.activeCameras[0];
  27618. }
  27619. else {
  27620. listeningCamera = this.activeCamera;
  27621. }
  27622. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27623. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27624. // for VR cameras
  27625. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27626. listeningCamera = listeningCamera.rigCameras[0];
  27627. }
  27628. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27629. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27630. cameraDirection.normalize();
  27631. // To avoid some errors on GearVR
  27632. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27633. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27634. }
  27635. var i;
  27636. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27637. var sound = this.mainSoundTrack.soundCollection[i];
  27638. if (sound.useCustomAttenuation) {
  27639. sound.updateDistanceFromListener();
  27640. }
  27641. }
  27642. for (i = 0; i < this.soundTracks.length; i++) {
  27643. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27644. sound = this.soundTracks[i].soundCollection[j];
  27645. if (sound.useCustomAttenuation) {
  27646. sound.updateDistanceFromListener();
  27647. }
  27648. }
  27649. }
  27650. }
  27651. };
  27652. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27653. // Audio
  27654. /**
  27655. * Gets or sets if audio support is enabled
  27656. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27657. */
  27658. get: function () {
  27659. return this._audioEnabled;
  27660. },
  27661. set: function (value) {
  27662. this._audioEnabled = value;
  27663. if (BABYLON.AudioEngine) {
  27664. if (this._audioEnabled) {
  27665. this._enableAudio();
  27666. }
  27667. else {
  27668. this._disableAudio();
  27669. }
  27670. }
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. Scene.prototype._disableAudio = function () {
  27676. var i;
  27677. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27678. this.mainSoundTrack.soundCollection[i].pause();
  27679. }
  27680. for (i = 0; i < this.soundTracks.length; i++) {
  27681. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27682. this.soundTracks[i].soundCollection[j].pause();
  27683. }
  27684. }
  27685. };
  27686. Scene.prototype._enableAudio = function () {
  27687. var i;
  27688. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27689. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27690. this.mainSoundTrack.soundCollection[i].play();
  27691. }
  27692. }
  27693. for (i = 0; i < this.soundTracks.length; i++) {
  27694. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27695. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27696. this.soundTracks[i].soundCollection[j].play();
  27697. }
  27698. }
  27699. }
  27700. };
  27701. Object.defineProperty(Scene.prototype, "headphone", {
  27702. /**
  27703. * Gets or sets if audio will be output to headphones
  27704. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27705. */
  27706. get: function () {
  27707. return this._headphone;
  27708. },
  27709. set: function (value) {
  27710. this._headphone = value;
  27711. if (BABYLON.AudioEngine) {
  27712. if (this._headphone) {
  27713. this._switchAudioModeForHeadphones();
  27714. }
  27715. else {
  27716. this._switchAudioModeForNormalSpeakers();
  27717. }
  27718. }
  27719. },
  27720. enumerable: true,
  27721. configurable: true
  27722. });
  27723. Scene.prototype._switchAudioModeForHeadphones = function () {
  27724. this.mainSoundTrack.switchPanningModelToHRTF();
  27725. for (var i = 0; i < this.soundTracks.length; i++) {
  27726. this.soundTracks[i].switchPanningModelToHRTF();
  27727. }
  27728. };
  27729. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27730. this.mainSoundTrack.switchPanningModelToEqualPower();
  27731. for (var i = 0; i < this.soundTracks.length; i++) {
  27732. this.soundTracks[i].switchPanningModelToEqualPower();
  27733. }
  27734. };
  27735. /**
  27736. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27737. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27738. * @returns the created depth renderer
  27739. */
  27740. Scene.prototype.enableDepthRenderer = function (camera) {
  27741. camera = camera || this.activeCamera;
  27742. if (!camera) {
  27743. throw "No camera available to enable depth renderer";
  27744. }
  27745. if (!this._depthRenderer[camera.id]) {
  27746. var textureType = 0;
  27747. if (this._engine.getCaps().textureHalfFloatRender) {
  27748. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27749. }
  27750. else if (this._engine.getCaps().textureFloatRender) {
  27751. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27752. }
  27753. else {
  27754. throw "Depth renderer does not support int texture type";
  27755. }
  27756. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27757. }
  27758. return this._depthRenderer[camera.id];
  27759. };
  27760. /**
  27761. * Disables a depth renderer for a given camera
  27762. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27763. */
  27764. Scene.prototype.disableDepthRenderer = function (camera) {
  27765. camera = camera || this.activeCamera;
  27766. if (!camera || !this._depthRenderer[camera.id]) {
  27767. return;
  27768. }
  27769. this._depthRenderer[camera.id].dispose();
  27770. delete this._depthRenderer[camera.id];
  27771. };
  27772. /**
  27773. * Enables a GeometryBufferRender and associates it with the scene
  27774. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27775. * @returns the GeometryBufferRenderer
  27776. */
  27777. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27778. if (ratio === void 0) { ratio = 1; }
  27779. if (this._geometryBufferRenderer) {
  27780. return this._geometryBufferRenderer;
  27781. }
  27782. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27783. if (!this._geometryBufferRenderer.isSupported) {
  27784. this._geometryBufferRenderer = null;
  27785. }
  27786. return this._geometryBufferRenderer;
  27787. };
  27788. /**
  27789. * Disables the GeometryBufferRender associated with the scene
  27790. */
  27791. Scene.prototype.disableGeometryBufferRenderer = function () {
  27792. if (!this._geometryBufferRenderer) {
  27793. return;
  27794. }
  27795. this._geometryBufferRenderer.dispose();
  27796. this._geometryBufferRenderer = null;
  27797. };
  27798. /**
  27799. * Freeze all materials
  27800. * A frozen material will not be updatable but should be faster to render
  27801. */
  27802. Scene.prototype.freezeMaterials = function () {
  27803. for (var i = 0; i < this.materials.length; i++) {
  27804. this.materials[i].freeze();
  27805. }
  27806. };
  27807. /**
  27808. * Unfreeze all materials
  27809. * A frozen material will not be updatable but should be faster to render
  27810. */
  27811. Scene.prototype.unfreezeMaterials = function () {
  27812. for (var i = 0; i < this.materials.length; i++) {
  27813. this.materials[i].unfreeze();
  27814. }
  27815. };
  27816. /**
  27817. * Releases all held ressources
  27818. */
  27819. Scene.prototype.dispose = function () {
  27820. this.beforeRender = null;
  27821. this.afterRender = null;
  27822. this.skeletons = [];
  27823. this.morphTargetManagers = [];
  27824. this.importedMeshesFiles = new Array();
  27825. this.stopAllAnimations();
  27826. this.resetCachedMaterial();
  27827. for (var key in this._depthRenderer) {
  27828. this._depthRenderer[key].dispose();
  27829. }
  27830. if (this._gamepadManager) {
  27831. this._gamepadManager.dispose();
  27832. this._gamepadManager = null;
  27833. }
  27834. // Smart arrays
  27835. if (this.activeCamera) {
  27836. this.activeCamera._activeMeshes.dispose();
  27837. this.activeCamera = null;
  27838. }
  27839. this._activeMeshes.dispose();
  27840. this._renderingManager.dispose();
  27841. this._processedMaterials.dispose();
  27842. this._activeParticleSystems.dispose();
  27843. this._activeSkeletons.dispose();
  27844. this._softwareSkinnedMeshes.dispose();
  27845. this._renderTargets.dispose();
  27846. this._registeredForLateAnimationBindings.dispose();
  27847. if (this._boundingBoxRenderer) {
  27848. this._boundingBoxRenderer.dispose();
  27849. }
  27850. this._meshesForIntersections.dispose();
  27851. this._toBeDisposed.dispose();
  27852. // Abort active requests
  27853. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27854. var request = _a[_i];
  27855. request.abort();
  27856. }
  27857. // Debug layer
  27858. if (this._debugLayer) {
  27859. this._debugLayer.hide();
  27860. }
  27861. // Events
  27862. this.onDisposeObservable.notifyObservers(this);
  27863. this.onDisposeObservable.clear();
  27864. this.onBeforeRenderObservable.clear();
  27865. this.onAfterRenderObservable.clear();
  27866. this.onBeforeRenderTargetsRenderObservable.clear();
  27867. this.onAfterRenderTargetsRenderObservable.clear();
  27868. this.onAfterStepObservable.clear();
  27869. this.onBeforeStepObservable.clear();
  27870. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27871. this.onAfterActiveMeshesEvaluationObservable.clear();
  27872. this.onBeforeParticlesRenderingObservable.clear();
  27873. this.onAfterParticlesRenderingObservable.clear();
  27874. this.onBeforeSpritesRenderingObservable.clear();
  27875. this.onAfterSpritesRenderingObservable.clear();
  27876. this.onBeforeDrawPhaseObservable.clear();
  27877. this.onAfterDrawPhaseObservable.clear();
  27878. this.onBeforePhysicsObservable.clear();
  27879. this.onAfterPhysicsObservable.clear();
  27880. this.onBeforeAnimationsObservable.clear();
  27881. this.onAfterAnimationsObservable.clear();
  27882. this.onDataLoadedObservable.clear();
  27883. this.detachControl();
  27884. // Release sounds & sounds tracks
  27885. if (BABYLON.AudioEngine) {
  27886. this.disposeSounds();
  27887. }
  27888. // VR Helper
  27889. if (this.VRHelper) {
  27890. this.VRHelper.dispose();
  27891. }
  27892. // Detach cameras
  27893. var canvas = this._engine.getRenderingCanvas();
  27894. if (canvas) {
  27895. var index;
  27896. for (index = 0; index < this.cameras.length; index++) {
  27897. this.cameras[index].detachControl(canvas);
  27898. }
  27899. }
  27900. // Release animation groups
  27901. while (this.animationGroups.length) {
  27902. this.animationGroups[0].dispose();
  27903. }
  27904. // Release lights
  27905. while (this.lights.length) {
  27906. this.lights[0].dispose();
  27907. }
  27908. // Release meshes
  27909. while (this.meshes.length) {
  27910. this.meshes[0].dispose(true);
  27911. }
  27912. while (this.transformNodes.length) {
  27913. this.removeTransformNode(this.transformNodes[0]);
  27914. }
  27915. // Release cameras
  27916. while (this.cameras.length) {
  27917. this.cameras[0].dispose();
  27918. }
  27919. // Release materials
  27920. if (this.defaultMaterial) {
  27921. this.defaultMaterial.dispose();
  27922. }
  27923. while (this.multiMaterials.length) {
  27924. this.multiMaterials[0].dispose();
  27925. }
  27926. while (this.materials.length) {
  27927. this.materials[0].dispose();
  27928. }
  27929. // Release particles
  27930. while (this.particleSystems.length) {
  27931. this.particleSystems[0].dispose();
  27932. }
  27933. // Release sprites
  27934. while (this.spriteManagers.length) {
  27935. this.spriteManagers[0].dispose();
  27936. }
  27937. // Release postProcesses
  27938. while (this.postProcesses.length) {
  27939. this.postProcesses[0].dispose();
  27940. }
  27941. // Release layers
  27942. while (this.layers.length) {
  27943. this.layers[0].dispose();
  27944. }
  27945. while (this.effectLayers.length) {
  27946. this.effectLayers[0].dispose();
  27947. }
  27948. // Release textures
  27949. while (this.textures.length) {
  27950. this.textures[0].dispose();
  27951. }
  27952. // Release UBO
  27953. this._sceneUbo.dispose();
  27954. if (this._alternateSceneUbo) {
  27955. this._alternateSceneUbo.dispose();
  27956. }
  27957. // Post-processes
  27958. this.postProcessManager.dispose();
  27959. if (this._postProcessRenderPipelineManager) {
  27960. this._postProcessRenderPipelineManager.dispose();
  27961. }
  27962. // Physics
  27963. if (this._physicsEngine) {
  27964. this.disablePhysicsEngine();
  27965. }
  27966. // Remove from engine
  27967. index = this._engine.scenes.indexOf(this);
  27968. if (index > -1) {
  27969. this._engine.scenes.splice(index, 1);
  27970. }
  27971. this._engine.wipeCaches(true);
  27972. this._isDisposed = true;
  27973. };
  27974. Object.defineProperty(Scene.prototype, "isDisposed", {
  27975. /**
  27976. * Gets if the scene is already disposed
  27977. */
  27978. get: function () {
  27979. return this._isDisposed;
  27980. },
  27981. enumerable: true,
  27982. configurable: true
  27983. });
  27984. /**
  27985. * Releases sounds & soundtracks
  27986. */
  27987. Scene.prototype.disposeSounds = function () {
  27988. if (!this._mainSoundTrack) {
  27989. return;
  27990. }
  27991. this.mainSoundTrack.dispose();
  27992. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27993. this.soundTracks[scIndex].dispose();
  27994. }
  27995. };
  27996. // Octrees
  27997. /**
  27998. * Get the world extend vectors with an optional filter
  27999. *
  28000. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28001. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28002. */
  28003. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28004. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28005. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28006. filterPredicate = filterPredicate || (function () { return true; });
  28007. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28008. mesh.computeWorldMatrix(true);
  28009. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28010. return;
  28011. }
  28012. var boundingInfo = mesh.getBoundingInfo();
  28013. var minBox = boundingInfo.boundingBox.minimumWorld;
  28014. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28015. BABYLON.Tools.CheckExtends(minBox, min, max);
  28016. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28017. });
  28018. return {
  28019. min: min,
  28020. max: max
  28021. };
  28022. };
  28023. /**
  28024. * Creates or updates the octree used to boost selection (picking)
  28025. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28026. * @param maxCapacity defines the maximum capacity per leaf
  28027. * @param maxDepth defines the maximum depth of the octree
  28028. * @returns an octree of AbstractMesh
  28029. */
  28030. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28031. if (maxCapacity === void 0) { maxCapacity = 64; }
  28032. if (maxDepth === void 0) { maxDepth = 2; }
  28033. if (!this._selectionOctree) {
  28034. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28035. }
  28036. var worldExtends = this.getWorldExtends();
  28037. // Update octree
  28038. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28039. return this._selectionOctree;
  28040. };
  28041. // Picking
  28042. /**
  28043. * Creates a ray that can be used to pick in the scene
  28044. * @param x defines the x coordinate of the origin (on-screen)
  28045. * @param y defines the y coordinate of the origin (on-screen)
  28046. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28047. * @param camera defines the camera to use for the picking
  28048. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28049. * @returns a Ray
  28050. */
  28051. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28052. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28053. var result = BABYLON.Ray.Zero();
  28054. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28055. return result;
  28056. };
  28057. /**
  28058. * Creates a ray that can be used to pick in the scene
  28059. * @param x defines the x coordinate of the origin (on-screen)
  28060. * @param y defines the y coordinate of the origin (on-screen)
  28061. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28062. * @param result defines the ray where to store the picking ray
  28063. * @param camera defines the camera to use for the picking
  28064. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28065. * @returns the current scene
  28066. */
  28067. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28068. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28069. var engine = this._engine;
  28070. if (!camera) {
  28071. if (!this.activeCamera)
  28072. throw new Error("Active camera not set");
  28073. camera = this.activeCamera;
  28074. }
  28075. var cameraViewport = camera.viewport;
  28076. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28077. // Moving coordinates to local viewport world
  28078. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28079. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28080. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28081. return this;
  28082. };
  28083. /**
  28084. * Creates a ray that can be used to pick in the scene
  28085. * @param x defines the x coordinate of the origin (on-screen)
  28086. * @param y defines the y coordinate of the origin (on-screen)
  28087. * @param camera defines the camera to use for the picking
  28088. * @returns a Ray
  28089. */
  28090. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28091. var result = BABYLON.Ray.Zero();
  28092. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28093. return result;
  28094. };
  28095. /**
  28096. * Creates a ray that can be used to pick in the scene
  28097. * @param x defines the x coordinate of the origin (on-screen)
  28098. * @param y defines the y coordinate of the origin (on-screen)
  28099. * @param result defines the ray where to store the picking ray
  28100. * @param camera defines the camera to use for the picking
  28101. * @returns the current scene
  28102. */
  28103. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28104. if (!BABYLON.PickingInfo) {
  28105. return this;
  28106. }
  28107. var engine = this._engine;
  28108. if (!camera) {
  28109. if (!this.activeCamera)
  28110. throw new Error("Active camera not set");
  28111. camera = this.activeCamera;
  28112. }
  28113. var cameraViewport = camera.viewport;
  28114. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28115. var identity = BABYLON.Matrix.Identity();
  28116. // Moving coordinates to local viewport world
  28117. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28118. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28119. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28120. return this;
  28121. };
  28122. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28123. if (!BABYLON.PickingInfo) {
  28124. return null;
  28125. }
  28126. var pickingInfo = null;
  28127. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28128. var mesh = this.meshes[meshIndex];
  28129. if (predicate) {
  28130. if (!predicate(mesh)) {
  28131. continue;
  28132. }
  28133. }
  28134. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28135. continue;
  28136. }
  28137. var world = mesh.getWorldMatrix();
  28138. var ray = rayFunction(world);
  28139. var result = mesh.intersects(ray, fastCheck);
  28140. if (!result || !result.hit)
  28141. continue;
  28142. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28143. continue;
  28144. pickingInfo = result;
  28145. if (fastCheck) {
  28146. break;
  28147. }
  28148. }
  28149. return pickingInfo || new BABYLON.PickingInfo();
  28150. };
  28151. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28152. if (!BABYLON.PickingInfo) {
  28153. return null;
  28154. }
  28155. var pickingInfos = new Array();
  28156. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28157. var mesh = this.meshes[meshIndex];
  28158. if (predicate) {
  28159. if (!predicate(mesh)) {
  28160. continue;
  28161. }
  28162. }
  28163. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28164. continue;
  28165. }
  28166. var world = mesh.getWorldMatrix();
  28167. var ray = rayFunction(world);
  28168. var result = mesh.intersects(ray, false);
  28169. if (!result || !result.hit)
  28170. continue;
  28171. pickingInfos.push(result);
  28172. }
  28173. return pickingInfos;
  28174. };
  28175. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28176. if (!BABYLON.PickingInfo) {
  28177. return null;
  28178. }
  28179. var pickingInfo = null;
  28180. if (!camera) {
  28181. if (!this.activeCamera) {
  28182. return null;
  28183. }
  28184. camera = this.activeCamera;
  28185. }
  28186. if (this.spriteManagers.length > 0) {
  28187. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28188. var spriteManager = this.spriteManagers[spriteIndex];
  28189. if (!spriteManager.isPickable) {
  28190. continue;
  28191. }
  28192. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28193. if (!result || !result.hit)
  28194. continue;
  28195. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28196. continue;
  28197. pickingInfo = result;
  28198. if (fastCheck) {
  28199. break;
  28200. }
  28201. }
  28202. }
  28203. return pickingInfo || new BABYLON.PickingInfo();
  28204. };
  28205. /** Launch a ray to try to pick a mesh in the scene
  28206. * @param x position on screen
  28207. * @param y position on screen
  28208. * @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
  28209. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28210. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28211. * @returns a PickingInfo
  28212. */
  28213. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28214. var _this = this;
  28215. if (!BABYLON.PickingInfo) {
  28216. return null;
  28217. }
  28218. return this._internalPick(function (world) {
  28219. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28220. return _this._tempPickingRay;
  28221. }, predicate, fastCheck);
  28222. };
  28223. /** Launch a ray to try to pick a sprite in the scene
  28224. * @param x position on screen
  28225. * @param y position on screen
  28226. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28227. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28228. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28229. * @returns a PickingInfo
  28230. */
  28231. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28232. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28233. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28234. };
  28235. /** Use the given ray to pick a mesh in the scene
  28236. * @param ray The ray to use to pick meshes
  28237. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28238. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28239. * @returns a PickingInfo
  28240. */
  28241. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28242. var _this = this;
  28243. return this._internalPick(function (world) {
  28244. if (!_this._pickWithRayInverseMatrix) {
  28245. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28246. }
  28247. world.invertToRef(_this._pickWithRayInverseMatrix);
  28248. if (!_this._cachedRayForTransform) {
  28249. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28250. }
  28251. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28252. return _this._cachedRayForTransform;
  28253. }, predicate, fastCheck);
  28254. };
  28255. /**
  28256. * Launch a ray to try to pick a mesh in the scene
  28257. * @param x X position on screen
  28258. * @param y Y position on screen
  28259. * @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
  28260. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28261. * @returns an array of PickingInfo
  28262. */
  28263. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28264. var _this = this;
  28265. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28266. };
  28267. /**
  28268. * Launch a ray to try to pick a mesh in the scene
  28269. * @param ray Ray to use
  28270. * @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
  28271. * @returns an array of PickingInfo
  28272. */
  28273. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28274. var _this = this;
  28275. return this._internalMultiPick(function (world) {
  28276. if (!_this._pickWithRayInverseMatrix) {
  28277. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28278. }
  28279. world.invertToRef(_this._pickWithRayInverseMatrix);
  28280. if (!_this._cachedRayForTransform) {
  28281. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28282. }
  28283. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28284. return _this._cachedRayForTransform;
  28285. }, predicate);
  28286. };
  28287. /**
  28288. * Force the value of meshUnderPointer
  28289. * @param mesh defines the mesh to use
  28290. */
  28291. Scene.prototype.setPointerOverMesh = function (mesh) {
  28292. if (this._pointerOverMesh === mesh) {
  28293. return;
  28294. }
  28295. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28296. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28297. }
  28298. this._pointerOverMesh = mesh;
  28299. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28300. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28301. }
  28302. };
  28303. /**
  28304. * Gets the mesh under the pointer
  28305. * @returns a Mesh or null if no mesh is under the pointer
  28306. */
  28307. Scene.prototype.getPointerOverMesh = function () {
  28308. return this._pointerOverMesh;
  28309. };
  28310. /**
  28311. * Force the sprite under the pointer
  28312. * @param sprite defines the sprite to use
  28313. */
  28314. Scene.prototype.setPointerOverSprite = function (sprite) {
  28315. if (this._pointerOverSprite === sprite) {
  28316. return;
  28317. }
  28318. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28319. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28320. }
  28321. this._pointerOverSprite = sprite;
  28322. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28323. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28324. }
  28325. };
  28326. /**
  28327. * Gets the sprite under the pointer
  28328. * @returns a Sprite or null if no sprite is under the pointer
  28329. */
  28330. Scene.prototype.getPointerOverSprite = function () {
  28331. return this._pointerOverSprite;
  28332. };
  28333. // Physics
  28334. /**
  28335. * Gets the current physics engine
  28336. * @returns a PhysicsEngine or null if none attached
  28337. */
  28338. Scene.prototype.getPhysicsEngine = function () {
  28339. return this._physicsEngine;
  28340. };
  28341. /**
  28342. * Enables physics to the current scene
  28343. * @param gravity defines the scene's gravity for the physics engine
  28344. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28345. * @return a boolean indicating if the physics engine was initialized
  28346. */
  28347. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28348. if (gravity === void 0) { gravity = null; }
  28349. if (this._physicsEngine) {
  28350. return true;
  28351. }
  28352. try {
  28353. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28354. return true;
  28355. }
  28356. catch (e) {
  28357. BABYLON.Tools.Error(e.message);
  28358. return false;
  28359. }
  28360. };
  28361. /**
  28362. * Disables and disposes the physics engine associated with the scene
  28363. */
  28364. Scene.prototype.disablePhysicsEngine = function () {
  28365. if (!this._physicsEngine) {
  28366. return;
  28367. }
  28368. this._physicsEngine.dispose();
  28369. this._physicsEngine = null;
  28370. };
  28371. /**
  28372. * Gets a boolean indicating if there is an active physics engine
  28373. * @returns a boolean indicating if there is an active physics engine
  28374. */
  28375. Scene.prototype.isPhysicsEnabled = function () {
  28376. return this._physicsEngine !== undefined;
  28377. };
  28378. /**
  28379. * Deletes a physics compound impostor
  28380. * @param compound defines the compound to delete
  28381. */
  28382. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28383. var mesh = compound.parts[0].mesh;
  28384. if (mesh.physicsImpostor) {
  28385. mesh.physicsImpostor.dispose( /*true*/);
  28386. mesh.physicsImpostor = null;
  28387. }
  28388. };
  28389. // Misc.
  28390. /** @hidden */
  28391. Scene.prototype._rebuildGeometries = function () {
  28392. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28393. var geometry = _a[_i];
  28394. geometry._rebuild();
  28395. }
  28396. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28397. var mesh = _c[_b];
  28398. mesh._rebuild();
  28399. }
  28400. if (this.postProcessManager) {
  28401. this.postProcessManager._rebuild();
  28402. }
  28403. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28404. var layer = _e[_d];
  28405. layer._rebuild();
  28406. }
  28407. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28408. var effectLayer = _g[_f];
  28409. effectLayer._rebuild();
  28410. }
  28411. if (this._boundingBoxRenderer) {
  28412. this._boundingBoxRenderer._rebuild();
  28413. }
  28414. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28415. var system = _j[_h];
  28416. system.rebuild();
  28417. }
  28418. if (this._postProcessRenderPipelineManager) {
  28419. this._postProcessRenderPipelineManager._rebuild();
  28420. }
  28421. };
  28422. /** @hidden */
  28423. Scene.prototype._rebuildTextures = function () {
  28424. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28425. var texture = _a[_i];
  28426. texture._rebuild();
  28427. }
  28428. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28429. };
  28430. /**
  28431. * Creates a default light for the scene.
  28432. * @param replace Whether to replace the existing lights in the scene.
  28433. */
  28434. Scene.prototype.createDefaultLight = function (replace) {
  28435. if (replace === void 0) { replace = false; }
  28436. // Dispose existing light in replace mode.
  28437. if (replace) {
  28438. if (this.lights) {
  28439. for (var i = 0; i < this.lights.length; i++) {
  28440. this.lights[i].dispose();
  28441. }
  28442. }
  28443. }
  28444. // Light
  28445. if (this.lights.length === 0) {
  28446. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28447. }
  28448. };
  28449. /**
  28450. * Creates a default camera for the scene.
  28451. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28452. * @param replace Whether to replace the existing active camera in the scene.
  28453. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28454. */
  28455. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28456. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28457. if (replace === void 0) { replace = false; }
  28458. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28459. // Dispose existing camera in replace mode.
  28460. if (replace) {
  28461. if (this.activeCamera) {
  28462. this.activeCamera.dispose();
  28463. this.activeCamera = null;
  28464. }
  28465. }
  28466. // Camera
  28467. if (!this.activeCamera) {
  28468. var worldExtends = this.getWorldExtends();
  28469. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28470. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28471. var camera;
  28472. var radius = worldSize.length() * 1.5;
  28473. // empty scene scenario!
  28474. if (!isFinite(radius)) {
  28475. radius = 1;
  28476. worldCenter.copyFromFloats(0, 0, 0);
  28477. }
  28478. if (createArcRotateCamera) {
  28479. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28480. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28481. arcRotateCamera.wheelPrecision = 100 / radius;
  28482. camera = arcRotateCamera;
  28483. }
  28484. else {
  28485. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28486. freeCamera.setTarget(worldCenter);
  28487. camera = freeCamera;
  28488. }
  28489. camera.minZ = radius * 0.01;
  28490. camera.maxZ = radius * 1000;
  28491. camera.speed = radius * 0.2;
  28492. this.activeCamera = camera;
  28493. var canvas = this.getEngine().getRenderingCanvas();
  28494. if (attachCameraControls && canvas) {
  28495. camera.attachControl(canvas);
  28496. }
  28497. }
  28498. };
  28499. /**
  28500. * Creates a default camera and a default light
  28501. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28502. * @param replace defines if the camera and/or light will replace the existing ones
  28503. * @param attachCameraControls defines if attachControl will be called on the new camera
  28504. */
  28505. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28506. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28507. if (replace === void 0) { replace = false; }
  28508. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28509. this.createDefaultLight(replace);
  28510. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28511. };
  28512. /**
  28513. * Creates a new sky box
  28514. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28515. * @param environmentTexture defines the texture to use as environment texture
  28516. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28517. * @param scale defines the overall scale of the skybox
  28518. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28519. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28520. * @returns a new mesh holding the sky box
  28521. */
  28522. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28523. if (pbr === void 0) { pbr = false; }
  28524. if (scale === void 0) { scale = 1000; }
  28525. if (blur === void 0) { blur = 0; }
  28526. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28527. if (!environmentTexture) {
  28528. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28529. return null;
  28530. }
  28531. if (setGlobalEnvTexture) {
  28532. if (environmentTexture) {
  28533. this.environmentTexture = environmentTexture;
  28534. }
  28535. }
  28536. // Skybox
  28537. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28538. if (pbr) {
  28539. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28540. hdrSkyboxMaterial.backFaceCulling = false;
  28541. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28542. if (hdrSkyboxMaterial.reflectionTexture) {
  28543. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28544. }
  28545. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28546. hdrSkyboxMaterial.disableLighting = true;
  28547. hdrSkyboxMaterial.twoSidedLighting = true;
  28548. hdrSkybox.infiniteDistance = true;
  28549. hdrSkybox.material = hdrSkyboxMaterial;
  28550. }
  28551. else {
  28552. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28553. skyboxMaterial.backFaceCulling = false;
  28554. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28555. if (skyboxMaterial.reflectionTexture) {
  28556. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28557. }
  28558. skyboxMaterial.disableLighting = true;
  28559. hdrSkybox.infiniteDistance = true;
  28560. hdrSkybox.material = skyboxMaterial;
  28561. }
  28562. return hdrSkybox;
  28563. };
  28564. /**
  28565. * Creates a new environment
  28566. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28567. * @param options defines the options you can use to configure the environment
  28568. * @returns the new EnvironmentHelper
  28569. */
  28570. Scene.prototype.createDefaultEnvironment = function (options) {
  28571. if (BABYLON.EnvironmentHelper) {
  28572. return new BABYLON.EnvironmentHelper(options, this);
  28573. }
  28574. return null;
  28575. };
  28576. /**
  28577. * Creates a new VREXperienceHelper
  28578. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28579. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28580. * @returns a new VREXperienceHelper
  28581. */
  28582. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28583. if (webVROptions === void 0) { webVROptions = {}; }
  28584. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28585. };
  28586. // Tags
  28587. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28588. if (tagsQuery === undefined) {
  28589. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28590. return list;
  28591. }
  28592. var listByTags = [];
  28593. forEach = forEach || (function (item) { return; });
  28594. for (var i in list) {
  28595. var item = list[i];
  28596. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28597. listByTags.push(item);
  28598. forEach(item);
  28599. }
  28600. }
  28601. return listByTags;
  28602. };
  28603. /**
  28604. * Get a list of meshes by tags
  28605. * @param tagsQuery defines the tags query to use
  28606. * @param forEach defines a predicate used to filter results
  28607. * @returns an array of Mesh
  28608. */
  28609. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28610. return this._getByTags(this.meshes, tagsQuery, forEach);
  28611. };
  28612. /**
  28613. * Get a list of cameras by tags
  28614. * @param tagsQuery defines the tags query to use
  28615. * @param forEach defines a predicate used to filter results
  28616. * @returns an array of Camera
  28617. */
  28618. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28619. return this._getByTags(this.cameras, tagsQuery, forEach);
  28620. };
  28621. /**
  28622. * Get a list of lights by tags
  28623. * @param tagsQuery defines the tags query to use
  28624. * @param forEach defines a predicate used to filter results
  28625. * @returns an array of Light
  28626. */
  28627. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28628. return this._getByTags(this.lights, tagsQuery, forEach);
  28629. };
  28630. /**
  28631. * Get a list of materials by tags
  28632. * @param tagsQuery defines the tags query to use
  28633. * @param forEach defines a predicate used to filter results
  28634. * @returns an array of Material
  28635. */
  28636. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28637. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28638. };
  28639. /**
  28640. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28641. * This allowed control for front to back rendering or reversly depending of the special needs.
  28642. *
  28643. * @param renderingGroupId The rendering group id corresponding to its index
  28644. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28645. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28646. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28647. */
  28648. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28649. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28650. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28651. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28652. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28653. };
  28654. /**
  28655. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28656. *
  28657. * @param renderingGroupId The rendering group id corresponding to its index
  28658. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28659. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28660. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28661. */
  28662. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28663. if (depth === void 0) { depth = true; }
  28664. if (stencil === void 0) { stencil = true; }
  28665. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28666. };
  28667. /**
  28668. * Will flag all materials as dirty to trigger new shader compilation
  28669. * @param flag defines the flag used to specify which material part must be marked as dirty
  28670. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28671. */
  28672. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28673. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28674. var material = _a[_i];
  28675. if (predicate && !predicate(material)) {
  28676. continue;
  28677. }
  28678. material.markAsDirty(flag);
  28679. }
  28680. };
  28681. /** @hidden */
  28682. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28683. var _this = this;
  28684. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28685. this._activeRequests.push(request);
  28686. request.onCompleteObservable.add(function (request) {
  28687. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28688. });
  28689. return request;
  28690. };
  28691. /** @hidden */
  28692. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28693. var _this = this;
  28694. return new Promise(function (resolve, reject) {
  28695. _this._loadFile(url, function (data) {
  28696. resolve(data);
  28697. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28698. reject(exception);
  28699. });
  28700. });
  28701. };
  28702. // Statics
  28703. Scene._FOGMODE_NONE = 0;
  28704. Scene._FOGMODE_EXP = 1;
  28705. Scene._FOGMODE_EXP2 = 2;
  28706. Scene._FOGMODE_LINEAR = 3;
  28707. Scene._uniqueIdCounter = 0;
  28708. /**
  28709. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28710. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28711. */
  28712. Scene.MinDeltaTime = 1.0;
  28713. /**
  28714. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28715. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28716. */
  28717. Scene.MaxDeltaTime = 1000.0;
  28718. /** The distance in pixel that you have to move to prevent some events */
  28719. Scene.DragMovementThreshold = 10; // in pixels
  28720. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28721. Scene.LongPressDelay = 500; // in milliseconds
  28722. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28723. Scene.DoubleClickDelay = 300; // in milliseconds
  28724. /** If you need to check double click without raising a single click at first click, enable this flag */
  28725. Scene.ExclusiveDoubleClickMode = false;
  28726. return Scene;
  28727. }());
  28728. BABYLON.Scene = Scene;
  28729. })(BABYLON || (BABYLON = {}));
  28730. //# sourceMappingURL=babylon.scene.js.map
  28731. var BABYLON;
  28732. (function (BABYLON) {
  28733. /**
  28734. * Set of assets to keep when moving a scene into an asset container.
  28735. */
  28736. var KeepAssets = /** @class */ (function () {
  28737. function KeepAssets() {
  28738. /**
  28739. * Cameras to keep.
  28740. */
  28741. this.cameras = new Array();
  28742. /**
  28743. * Lights to keep.
  28744. */
  28745. this.lights = new Array();
  28746. /**
  28747. * Meshes to keep.
  28748. */
  28749. this.meshes = new Array();
  28750. /**
  28751. * Skeletons to keep.
  28752. */
  28753. this.skeletons = new Array();
  28754. /**
  28755. * ParticleSystems to keep.
  28756. */
  28757. this.particleSystems = new Array();
  28758. /**
  28759. * Animations to keep.
  28760. */
  28761. this.animations = new Array();
  28762. /**
  28763. * AnimationGroups to keep.
  28764. */
  28765. this.animationGroups = new Array();
  28766. /**
  28767. * MultiMaterials to keep.
  28768. */
  28769. this.multiMaterials = new Array();
  28770. /**
  28771. * Materials to keep.
  28772. */
  28773. this.materials = new Array();
  28774. /**
  28775. * MorphTargetManagers to keep.
  28776. */
  28777. this.morphTargetManagers = new Array();
  28778. /**
  28779. * Geometries to keep.
  28780. */
  28781. this.geometries = new Array();
  28782. /**
  28783. * TransformNodes to keep.
  28784. */
  28785. this.transformNodes = new Array();
  28786. /**
  28787. * LensFlareSystems to keep.
  28788. */
  28789. this.lensFlareSystems = new Array();
  28790. /**
  28791. * ShadowGenerators to keep.
  28792. */
  28793. this.shadowGenerators = new Array();
  28794. /**
  28795. * ActionManagers to keep.
  28796. */
  28797. this.actionManagers = new Array();
  28798. /**
  28799. * Sounds to keep.
  28800. */
  28801. this.sounds = new Array();
  28802. /**
  28803. * Textures to keep.
  28804. */
  28805. this.textures = new Array();
  28806. /**
  28807. * Effect layers to keep.
  28808. */
  28809. this.effectLayers = new Array();
  28810. }
  28811. return KeepAssets;
  28812. }());
  28813. BABYLON.KeepAssets = KeepAssets;
  28814. /**
  28815. * Container with a set of assets that can be added or removed from a scene.
  28816. */
  28817. var AssetContainer = /** @class */ (function () {
  28818. /**
  28819. * Instantiates an AssetContainer.
  28820. * @param scene The scene the AssetContainer belongs to.
  28821. */
  28822. function AssetContainer(scene) {
  28823. // Objects
  28824. /**
  28825. * Cameras populated in the container.
  28826. */
  28827. this.cameras = new Array();
  28828. /**
  28829. * Lights populated in the container.
  28830. */
  28831. this.lights = new Array();
  28832. /**
  28833. * Meshes populated in the container.
  28834. */
  28835. this.meshes = new Array();
  28836. /**
  28837. * Skeletons populated in the container.
  28838. */
  28839. this.skeletons = new Array();
  28840. /**
  28841. * ParticleSystems populated in the container.
  28842. */
  28843. this.particleSystems = new Array();
  28844. /**
  28845. * Animations populated in the container.
  28846. */
  28847. this.animations = new Array();
  28848. /**
  28849. * AnimationGroups populated in the container.
  28850. */
  28851. this.animationGroups = new Array();
  28852. /**
  28853. * MultiMaterials populated in the container.
  28854. */
  28855. this.multiMaterials = new Array();
  28856. /**
  28857. * Materials populated in the container.
  28858. */
  28859. this.materials = new Array();
  28860. /**
  28861. * MorphTargetManagers populated in the container.
  28862. */
  28863. this.morphTargetManagers = new Array();
  28864. /**
  28865. * Geometries populated in the container.
  28866. */
  28867. this.geometries = new Array();
  28868. /**
  28869. * TransformNodes populated in the container.
  28870. */
  28871. this.transformNodes = new Array();
  28872. /**
  28873. * LensFlareSystems populated in the container.
  28874. */
  28875. this.lensFlareSystems = new Array();
  28876. /**
  28877. * ShadowGenerators populated in the container.
  28878. */
  28879. this.shadowGenerators = new Array();
  28880. /**
  28881. * ActionManagers populated in the container.
  28882. */
  28883. this.actionManagers = new Array();
  28884. /**
  28885. * Sounds populated in the container.
  28886. */
  28887. this.sounds = new Array();
  28888. /**
  28889. * Textures populated in the container.
  28890. */
  28891. this.textures = new Array();
  28892. /**
  28893. * Effect layers populated in the container.
  28894. */
  28895. this.effectLayers = new Array();
  28896. this.scene = scene;
  28897. }
  28898. /**
  28899. * Adds all the assets from the container to the scene.
  28900. */
  28901. AssetContainer.prototype.addAllToScene = function () {
  28902. var _this = this;
  28903. this.cameras.forEach(function (o) {
  28904. _this.scene.addCamera(o);
  28905. });
  28906. this.lights.forEach(function (o) {
  28907. _this.scene.addLight(o);
  28908. });
  28909. this.meshes.forEach(function (o) {
  28910. _this.scene.addMesh(o);
  28911. });
  28912. this.skeletons.forEach(function (o) {
  28913. _this.scene.addSkeleton(o);
  28914. });
  28915. this.particleSystems.forEach(function (o) {
  28916. _this.scene.addParticleSystem(o);
  28917. });
  28918. this.animations.forEach(function (o) {
  28919. _this.scene.addAnimation(o);
  28920. });
  28921. this.animationGroups.forEach(function (o) {
  28922. _this.scene.addAnimationGroup(o);
  28923. });
  28924. this.multiMaterials.forEach(function (o) {
  28925. _this.scene.addMultiMaterial(o);
  28926. });
  28927. this.materials.forEach(function (o) {
  28928. _this.scene.addMaterial(o);
  28929. });
  28930. this.morphTargetManagers.forEach(function (o) {
  28931. _this.scene.addMorphTargetManager(o);
  28932. });
  28933. this.geometries.forEach(function (o) {
  28934. _this.scene.addGeometry(o);
  28935. });
  28936. this.transformNodes.forEach(function (o) {
  28937. _this.scene.addTransformNode(o);
  28938. });
  28939. this.lensFlareSystems.forEach(function (o) {
  28940. _this.scene.addLensFlareSystem(o);
  28941. });
  28942. this.actionManagers.forEach(function (o) {
  28943. _this.scene.addActionManager(o);
  28944. });
  28945. this.sounds.forEach(function (o) {
  28946. o.play();
  28947. o.autoplay = true;
  28948. _this.scene.mainSoundTrack.AddSound(o);
  28949. });
  28950. this.textures.forEach(function (o) {
  28951. _this.scene.addTexture(o);
  28952. });
  28953. this.effectLayers.forEach(function (o) {
  28954. _this.scene.addEffectLayer(o);
  28955. });
  28956. };
  28957. /**
  28958. * Removes all the assets in the container from the scene
  28959. */
  28960. AssetContainer.prototype.removeAllFromScene = function () {
  28961. var _this = this;
  28962. this.cameras.forEach(function (o) {
  28963. _this.scene.removeCamera(o);
  28964. });
  28965. this.lights.forEach(function (o) {
  28966. _this.scene.removeLight(o);
  28967. });
  28968. this.meshes.forEach(function (o) {
  28969. _this.scene.removeMesh(o);
  28970. });
  28971. this.skeletons.forEach(function (o) {
  28972. _this.scene.removeSkeleton(o);
  28973. });
  28974. this.particleSystems.forEach(function (o) {
  28975. _this.scene.removeParticleSystem(o);
  28976. });
  28977. this.animations.forEach(function (o) {
  28978. _this.scene.removeAnimation(o);
  28979. });
  28980. this.animationGroups.forEach(function (o) {
  28981. _this.scene.removeAnimationGroup(o);
  28982. });
  28983. this.multiMaterials.forEach(function (o) {
  28984. _this.scene.removeMultiMaterial(o);
  28985. });
  28986. this.materials.forEach(function (o) {
  28987. _this.scene.removeMaterial(o);
  28988. });
  28989. this.morphTargetManagers.forEach(function (o) {
  28990. _this.scene.removeMorphTargetManager(o);
  28991. });
  28992. this.geometries.forEach(function (o) {
  28993. _this.scene.removeGeometry(o);
  28994. });
  28995. this.transformNodes.forEach(function (o) {
  28996. _this.scene.removeTransformNode(o);
  28997. });
  28998. this.lensFlareSystems.forEach(function (o) {
  28999. _this.scene.removeLensFlareSystem(o);
  29000. });
  29001. this.actionManagers.forEach(function (o) {
  29002. _this.scene.removeActionManager(o);
  29003. });
  29004. this.sounds.forEach(function (o) {
  29005. o.stop();
  29006. o.autoplay = false;
  29007. _this.scene.mainSoundTrack.RemoveSound(o);
  29008. });
  29009. this.textures.forEach(function (o) {
  29010. _this.scene.removeTexture(o);
  29011. });
  29012. this.effectLayers.forEach(function (o) {
  29013. _this.scene.removeEffectLayer(o);
  29014. });
  29015. };
  29016. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29017. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29018. var asset = sourceAssets_1[_i];
  29019. var move = true;
  29020. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29021. var keepAsset = keepAssets_1[_a];
  29022. if (asset === keepAsset) {
  29023. move = false;
  29024. break;
  29025. }
  29026. }
  29027. if (move) {
  29028. targetAssets.push(asset);
  29029. }
  29030. }
  29031. };
  29032. /**
  29033. * Removes all the assets contained in the scene and adds them to the container.
  29034. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29035. */
  29036. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29037. if (keepAssets === undefined) {
  29038. keepAssets = new KeepAssets();
  29039. }
  29040. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29041. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29042. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29043. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29044. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29045. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29046. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29047. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29048. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29049. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29050. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29051. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29052. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29053. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29054. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29055. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29056. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29057. this.removeAllFromScene();
  29058. };
  29059. return AssetContainer;
  29060. }());
  29061. BABYLON.AssetContainer = AssetContainer;
  29062. })(BABYLON || (BABYLON = {}));
  29063. //# sourceMappingURL=babylon.assetContainer.js.map
  29064. var BABYLON;
  29065. (function (BABYLON) {
  29066. var Buffer = /** @class */ (function () {
  29067. /**
  29068. * Constructor
  29069. * @param engine the engine
  29070. * @param data the data to use for this buffer
  29071. * @param updatable whether the data is updatable
  29072. * @param stride the stride (optional)
  29073. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29074. * @param instanced whether the buffer is instanced (optional)
  29075. * @param useBytes set to true if the stride in in bytes (optional)
  29076. */
  29077. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29078. if (stride === void 0) { stride = 0; }
  29079. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29080. if (instanced === void 0) { instanced = false; }
  29081. if (useBytes === void 0) { useBytes = false; }
  29082. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29083. this._engine = engine.getScene().getEngine();
  29084. }
  29085. else {
  29086. this._engine = engine;
  29087. }
  29088. this._updatable = updatable;
  29089. this._instanced = instanced;
  29090. this._data = data;
  29091. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29092. if (!postponeInternalCreation) { // by default
  29093. this.create();
  29094. }
  29095. }
  29096. /**
  29097. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29098. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29099. * @param offset defines offset in the buffer (0 by default)
  29100. * @param size defines the size in floats of attributes (position is 3 for instance)
  29101. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29102. * @param instanced defines if the vertex buffer contains indexed data
  29103. * @param useBytes defines if the offset and stride are in bytes
  29104. * @returns the new vertex buffer
  29105. */
  29106. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29107. if (useBytes === void 0) { useBytes = false; }
  29108. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29109. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29110. // a lot of these parameters are ignored as they are overriden by the buffer
  29111. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29112. };
  29113. // Properties
  29114. Buffer.prototype.isUpdatable = function () {
  29115. return this._updatable;
  29116. };
  29117. Buffer.prototype.getData = function () {
  29118. return this._data;
  29119. };
  29120. Buffer.prototype.getBuffer = function () {
  29121. return this._buffer;
  29122. };
  29123. /**
  29124. * Gets the stride in float32 units (i.e. byte stride / 4).
  29125. * May not be an integer if the byte stride is not divisible by 4.
  29126. * DEPRECATED. Use byteStride instead.
  29127. * @returns the stride in float32 units
  29128. */
  29129. Buffer.prototype.getStrideSize = function () {
  29130. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29131. };
  29132. // Methods
  29133. Buffer.prototype.create = function (data) {
  29134. if (data === void 0) { data = null; }
  29135. if (!data && this._buffer) {
  29136. return; // nothing to do
  29137. }
  29138. data = data || this._data;
  29139. if (!data) {
  29140. return;
  29141. }
  29142. if (!this._buffer) { // create buffer
  29143. if (this._updatable) {
  29144. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29145. this._data = data;
  29146. }
  29147. else {
  29148. this._buffer = this._engine.createVertexBuffer(data);
  29149. }
  29150. }
  29151. else if (this._updatable) { // update buffer
  29152. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29153. this._data = data;
  29154. }
  29155. };
  29156. Buffer.prototype._rebuild = function () {
  29157. this._buffer = null;
  29158. this.create(this._data);
  29159. };
  29160. Buffer.prototype.update = function (data) {
  29161. this.create(data);
  29162. };
  29163. /**
  29164. * Updates the data directly.
  29165. * @param data the new data
  29166. * @param offset the new offset
  29167. * @param vertexCount the vertex count (optional)
  29168. * @param useBytes set to true if the offset is in bytes
  29169. */
  29170. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29171. if (useBytes === void 0) { useBytes = false; }
  29172. if (!this._buffer) {
  29173. return;
  29174. }
  29175. if (this._updatable) { // update buffer
  29176. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29177. this._data = null;
  29178. }
  29179. };
  29180. Buffer.prototype.dispose = function () {
  29181. if (!this._buffer) {
  29182. return;
  29183. }
  29184. if (this._engine._releaseBuffer(this._buffer)) {
  29185. this._buffer = null;
  29186. }
  29187. };
  29188. return Buffer;
  29189. }());
  29190. BABYLON.Buffer = Buffer;
  29191. })(BABYLON || (BABYLON = {}));
  29192. //# sourceMappingURL=babylon.buffer.js.map
  29193. var BABYLON;
  29194. (function (BABYLON) {
  29195. var VertexBuffer = /** @class */ (function () {
  29196. /**
  29197. * Constructor
  29198. * @param engine the engine
  29199. * @param data the data to use for this vertex buffer
  29200. * @param kind the vertex buffer kind
  29201. * @param updatable whether the data is updatable
  29202. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29203. * @param stride the stride (optional)
  29204. * @param instanced whether the buffer is instanced (optional)
  29205. * @param offset the offset of the data (optional)
  29206. * @param size the number of components (optional)
  29207. * @param type the type of the component (optional)
  29208. * @param normalized whether the data contains normalized data (optional)
  29209. * @param useBytes set to true if stride and offset are in bytes (optional)
  29210. */
  29211. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29212. if (normalized === void 0) { normalized = false; }
  29213. if (useBytes === void 0) { useBytes = false; }
  29214. if (data instanceof BABYLON.Buffer) {
  29215. this._buffer = data;
  29216. this._ownsBuffer = false;
  29217. }
  29218. else {
  29219. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29220. this._ownsBuffer = true;
  29221. }
  29222. this._kind = kind;
  29223. if (type == undefined) {
  29224. var data_1 = this.getData();
  29225. this.type = VertexBuffer.FLOAT;
  29226. if (data_1 instanceof Int8Array)
  29227. this.type = VertexBuffer.BYTE;
  29228. else if (data_1 instanceof Uint8Array)
  29229. this.type = VertexBuffer.UNSIGNED_BYTE;
  29230. else if (data_1 instanceof Int16Array)
  29231. this.type = VertexBuffer.SHORT;
  29232. else if (data_1 instanceof Uint16Array)
  29233. this.type = VertexBuffer.UNSIGNED_SHORT;
  29234. else if (data_1 instanceof Int32Array)
  29235. this.type = VertexBuffer.INT;
  29236. else if (data_1 instanceof Uint32Array)
  29237. this.type = VertexBuffer.UNSIGNED_INT;
  29238. }
  29239. else {
  29240. this.type = type;
  29241. }
  29242. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29243. if (useBytes) {
  29244. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29245. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29246. this.byteOffset = offset || 0;
  29247. }
  29248. else {
  29249. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29250. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29251. this.byteOffset = (offset || 0) * typeByteLength;
  29252. }
  29253. this.normalized = normalized;
  29254. this._instanced = instanced !== undefined ? instanced : false;
  29255. this._instanceDivisor = instanced ? 1 : 0;
  29256. }
  29257. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29258. /**
  29259. * Gets or sets the instance divisor when in instanced mode
  29260. */
  29261. get: function () {
  29262. return this._instanceDivisor;
  29263. },
  29264. set: function (value) {
  29265. this._instanceDivisor = value;
  29266. if (value == 0) {
  29267. this._instanced = false;
  29268. }
  29269. else {
  29270. this._instanced = true;
  29271. }
  29272. },
  29273. enumerable: true,
  29274. configurable: true
  29275. });
  29276. VertexBuffer.prototype._rebuild = function () {
  29277. if (!this._buffer) {
  29278. return;
  29279. }
  29280. this._buffer._rebuild();
  29281. };
  29282. /**
  29283. * Returns the kind of the VertexBuffer (string).
  29284. */
  29285. VertexBuffer.prototype.getKind = function () {
  29286. return this._kind;
  29287. };
  29288. // Properties
  29289. /**
  29290. * Boolean : is the VertexBuffer updatable ?
  29291. */
  29292. VertexBuffer.prototype.isUpdatable = function () {
  29293. return this._buffer.isUpdatable();
  29294. };
  29295. /**
  29296. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29297. */
  29298. VertexBuffer.prototype.getData = function () {
  29299. return this._buffer.getData();
  29300. };
  29301. /**
  29302. * Returns the WebGLBuffer associated to the VertexBuffer.
  29303. */
  29304. VertexBuffer.prototype.getBuffer = function () {
  29305. return this._buffer.getBuffer();
  29306. };
  29307. /**
  29308. * Returns the stride as a multiple of the type byte length.
  29309. * DEPRECATED. Use byteStride instead.
  29310. */
  29311. VertexBuffer.prototype.getStrideSize = function () {
  29312. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29313. };
  29314. /**
  29315. * Returns the offset as a multiple of the type byte length.
  29316. * DEPRECATED. Use byteOffset instead.
  29317. */
  29318. VertexBuffer.prototype.getOffset = function () {
  29319. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29320. };
  29321. /**
  29322. * Returns the number of components per vertex attribute (integer).
  29323. */
  29324. VertexBuffer.prototype.getSize = function () {
  29325. return this._size;
  29326. };
  29327. /**
  29328. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29329. */
  29330. VertexBuffer.prototype.getIsInstanced = function () {
  29331. return this._instanced;
  29332. };
  29333. /**
  29334. * Returns the instancing divisor, zero for non-instanced (integer).
  29335. */
  29336. VertexBuffer.prototype.getInstanceDivisor = function () {
  29337. return this._instanceDivisor;
  29338. };
  29339. // Methods
  29340. /**
  29341. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29342. * Returns the created WebGLBuffer.
  29343. */
  29344. VertexBuffer.prototype.create = function (data) {
  29345. return this._buffer.create(data);
  29346. };
  29347. /**
  29348. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29349. * This function will create a new buffer if the current one is not updatable
  29350. * Returns the updated WebGLBuffer.
  29351. */
  29352. VertexBuffer.prototype.update = function (data) {
  29353. return this._buffer.update(data);
  29354. };
  29355. /**
  29356. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29357. * Returns the directly updated WebGLBuffer.
  29358. * @param data the new data
  29359. * @param offset the new offset
  29360. * @param useBytes set to true if the offset is in bytes
  29361. */
  29362. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29363. if (useBytes === void 0) { useBytes = false; }
  29364. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29365. };
  29366. /**
  29367. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29368. */
  29369. VertexBuffer.prototype.dispose = function () {
  29370. if (this._ownsBuffer) {
  29371. this._buffer.dispose();
  29372. }
  29373. };
  29374. /**
  29375. * Enumerates each value of this vertex buffer as numbers.
  29376. * @param count the number of values to enumerate
  29377. * @param callback the callback function called for each value
  29378. */
  29379. VertexBuffer.prototype.forEach = function (count, callback) {
  29380. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29381. };
  29382. Object.defineProperty(VertexBuffer, "PositionKind", {
  29383. get: function () {
  29384. return VertexBuffer._PositionKind;
  29385. },
  29386. enumerable: true,
  29387. configurable: true
  29388. });
  29389. Object.defineProperty(VertexBuffer, "NormalKind", {
  29390. get: function () {
  29391. return VertexBuffer._NormalKind;
  29392. },
  29393. enumerable: true,
  29394. configurable: true
  29395. });
  29396. Object.defineProperty(VertexBuffer, "TangentKind", {
  29397. get: function () {
  29398. return VertexBuffer._TangentKind;
  29399. },
  29400. enumerable: true,
  29401. configurable: true
  29402. });
  29403. Object.defineProperty(VertexBuffer, "UVKind", {
  29404. get: function () {
  29405. return VertexBuffer._UVKind;
  29406. },
  29407. enumerable: true,
  29408. configurable: true
  29409. });
  29410. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29411. get: function () {
  29412. return VertexBuffer._UV2Kind;
  29413. },
  29414. enumerable: true,
  29415. configurable: true
  29416. });
  29417. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29418. get: function () {
  29419. return VertexBuffer._UV3Kind;
  29420. },
  29421. enumerable: true,
  29422. configurable: true
  29423. });
  29424. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29425. get: function () {
  29426. return VertexBuffer._UV4Kind;
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29432. get: function () {
  29433. return VertexBuffer._UV5Kind;
  29434. },
  29435. enumerable: true,
  29436. configurable: true
  29437. });
  29438. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29439. get: function () {
  29440. return VertexBuffer._UV6Kind;
  29441. },
  29442. enumerable: true,
  29443. configurable: true
  29444. });
  29445. Object.defineProperty(VertexBuffer, "ColorKind", {
  29446. get: function () {
  29447. return VertexBuffer._ColorKind;
  29448. },
  29449. enumerable: true,
  29450. configurable: true
  29451. });
  29452. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29453. get: function () {
  29454. return VertexBuffer._MatricesIndicesKind;
  29455. },
  29456. enumerable: true,
  29457. configurable: true
  29458. });
  29459. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29460. get: function () {
  29461. return VertexBuffer._MatricesWeightsKind;
  29462. },
  29463. enumerable: true,
  29464. configurable: true
  29465. });
  29466. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29467. get: function () {
  29468. return VertexBuffer._MatricesIndicesExtraKind;
  29469. },
  29470. enumerable: true,
  29471. configurable: true
  29472. });
  29473. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29474. get: function () {
  29475. return VertexBuffer._MatricesWeightsExtraKind;
  29476. },
  29477. enumerable: true,
  29478. configurable: true
  29479. });
  29480. /**
  29481. * Deduces the stride given a kind.
  29482. * @param kind The kind string to deduce
  29483. * @returns The deduced stride
  29484. */
  29485. VertexBuffer.DeduceStride = function (kind) {
  29486. switch (kind) {
  29487. case VertexBuffer.UVKind:
  29488. case VertexBuffer.UV2Kind:
  29489. case VertexBuffer.UV3Kind:
  29490. case VertexBuffer.UV4Kind:
  29491. case VertexBuffer.UV5Kind:
  29492. case VertexBuffer.UV6Kind:
  29493. return 2;
  29494. case VertexBuffer.NormalKind:
  29495. case VertexBuffer.PositionKind:
  29496. return 3;
  29497. case VertexBuffer.ColorKind:
  29498. case VertexBuffer.MatricesIndicesKind:
  29499. case VertexBuffer.MatricesIndicesExtraKind:
  29500. case VertexBuffer.MatricesWeightsKind:
  29501. case VertexBuffer.MatricesWeightsExtraKind:
  29502. case VertexBuffer.TangentKind:
  29503. return 4;
  29504. default:
  29505. throw new Error("Invalid kind '" + kind + "'");
  29506. }
  29507. };
  29508. /**
  29509. * Gets the byte length of the given type.
  29510. * @param type the type
  29511. * @returns the number of bytes
  29512. */
  29513. VertexBuffer.GetTypeByteLength = function (type) {
  29514. switch (type) {
  29515. case VertexBuffer.BYTE:
  29516. case VertexBuffer.UNSIGNED_BYTE:
  29517. return 1;
  29518. case VertexBuffer.SHORT:
  29519. case VertexBuffer.UNSIGNED_SHORT:
  29520. return 2;
  29521. case VertexBuffer.INT:
  29522. case VertexBuffer.FLOAT:
  29523. return 4;
  29524. default:
  29525. throw new Error("Invalid type '" + type + "'");
  29526. }
  29527. };
  29528. /**
  29529. * Enumerates each value of the given parameters as numbers.
  29530. * @param data the data to enumerate
  29531. * @param byteOffset the byte offset of the data
  29532. * @param byteStride the byte stride of the data
  29533. * @param componentCount the number of components per element
  29534. * @param componentType the type of the component
  29535. * @param count the total number of components
  29536. * @param normalized whether the data is normalized
  29537. * @param callback the callback function called for each value
  29538. */
  29539. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29540. if (data instanceof Array) {
  29541. var offset = byteOffset / 4;
  29542. var stride = byteStride / 4;
  29543. for (var index = 0; index < count; index += componentCount) {
  29544. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29545. callback(data[offset + componentIndex], index + componentIndex);
  29546. }
  29547. offset += stride;
  29548. }
  29549. }
  29550. else {
  29551. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29552. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29553. for (var index = 0; index < count; index += componentCount) {
  29554. var componentByteOffset = byteOffset;
  29555. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29556. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29557. callback(value, index + componentIndex);
  29558. componentByteOffset += componentByteLength;
  29559. }
  29560. byteOffset += byteStride;
  29561. }
  29562. }
  29563. };
  29564. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29565. switch (type) {
  29566. case VertexBuffer.BYTE: {
  29567. var value = dataView.getInt8(byteOffset);
  29568. if (normalized) {
  29569. value = (value + 0.5) / 127.5;
  29570. }
  29571. return value;
  29572. }
  29573. case VertexBuffer.UNSIGNED_BYTE: {
  29574. var value = dataView.getUint8(byteOffset);
  29575. if (normalized) {
  29576. value = value / 255;
  29577. }
  29578. return value;
  29579. }
  29580. case VertexBuffer.SHORT: {
  29581. var value = dataView.getInt16(byteOffset, true);
  29582. if (normalized) {
  29583. value = (value + 0.5) / 16383.5;
  29584. }
  29585. return value;
  29586. }
  29587. case VertexBuffer.UNSIGNED_SHORT: {
  29588. var value = dataView.getUint16(byteOffset, true);
  29589. if (normalized) {
  29590. value = value / 65535;
  29591. }
  29592. return value;
  29593. }
  29594. case VertexBuffer.FLOAT: {
  29595. return dataView.getFloat32(byteOffset, true);
  29596. }
  29597. default: {
  29598. throw new Error("Invalid component type " + type);
  29599. }
  29600. }
  29601. };
  29602. /**
  29603. * The byte type.
  29604. */
  29605. VertexBuffer.BYTE = 5120;
  29606. /**
  29607. * The unsigned byte type.
  29608. */
  29609. VertexBuffer.UNSIGNED_BYTE = 5121;
  29610. /**
  29611. * The short type.
  29612. */
  29613. VertexBuffer.SHORT = 5122;
  29614. /**
  29615. * The unsigned short type.
  29616. */
  29617. VertexBuffer.UNSIGNED_SHORT = 5123;
  29618. /**
  29619. * The integer type.
  29620. */
  29621. VertexBuffer.INT = 5124;
  29622. /**
  29623. * The unsigned integer type.
  29624. */
  29625. VertexBuffer.UNSIGNED_INT = 5125;
  29626. /**
  29627. * The float type.
  29628. */
  29629. VertexBuffer.FLOAT = 5126;
  29630. // Enums
  29631. VertexBuffer._PositionKind = "position";
  29632. VertexBuffer._NormalKind = "normal";
  29633. VertexBuffer._TangentKind = "tangent";
  29634. VertexBuffer._UVKind = "uv";
  29635. VertexBuffer._UV2Kind = "uv2";
  29636. VertexBuffer._UV3Kind = "uv3";
  29637. VertexBuffer._UV4Kind = "uv4";
  29638. VertexBuffer._UV5Kind = "uv5";
  29639. VertexBuffer._UV6Kind = "uv6";
  29640. VertexBuffer._ColorKind = "color";
  29641. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29642. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29643. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29644. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29645. return VertexBuffer;
  29646. }());
  29647. BABYLON.VertexBuffer = VertexBuffer;
  29648. })(BABYLON || (BABYLON = {}));
  29649. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29650. var BABYLON;
  29651. (function (BABYLON) {
  29652. /**
  29653. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29654. */
  29655. var DummyInternalTextureTracker = /** @class */ (function () {
  29656. function DummyInternalTextureTracker() {
  29657. /**
  29658. * Gets or set the previous tracker in the list
  29659. */
  29660. this.previous = null;
  29661. /**
  29662. * Gets or set the next tracker in the list
  29663. */
  29664. this.next = null;
  29665. }
  29666. return DummyInternalTextureTracker;
  29667. }());
  29668. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29669. })(BABYLON || (BABYLON = {}));
  29670. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29671. var BABYLON;
  29672. (function (BABYLON) {
  29673. /**
  29674. * Class used to store data associated with WebGL texture data for the engine
  29675. * This class should not be used directly
  29676. */
  29677. var InternalTexture = /** @class */ (function () {
  29678. /**
  29679. * Creates a new InternalTexture
  29680. * @param engine defines the engine to use
  29681. * @param dataSource defines the type of data that will be used
  29682. */
  29683. function InternalTexture(engine, dataSource) {
  29684. /**
  29685. * Observable called when the texture is loaded
  29686. */
  29687. this.onLoadedObservable = new BABYLON.Observable();
  29688. /**
  29689. * Gets or set the previous tracker in the list
  29690. */
  29691. this.previous = null;
  29692. /**
  29693. * Gets or set the next tracker in the list
  29694. */
  29695. this.next = null;
  29696. // Private
  29697. /** @hidden */
  29698. this._initialSlot = -1;
  29699. /** @hidden */
  29700. this._designatedSlot = -1;
  29701. /** @hidden */
  29702. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29703. /** @hidden */
  29704. this._comparisonFunction = 0;
  29705. /** @hidden */
  29706. this._references = 1;
  29707. this._engine = engine;
  29708. this._dataSource = dataSource;
  29709. this._webGLTexture = engine._createTexture();
  29710. }
  29711. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29712. /**
  29713. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29714. */
  29715. get: function () {
  29716. return this._dataSource;
  29717. },
  29718. enumerable: true,
  29719. configurable: true
  29720. });
  29721. /**
  29722. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29723. */
  29724. InternalTexture.prototype.incrementReferences = function () {
  29725. this._references++;
  29726. };
  29727. /**
  29728. * Change the size of the texture (not the size of the content)
  29729. * @param width defines the new width
  29730. * @param height defines the new height
  29731. * @param depth defines the new depth (1 by default)
  29732. */
  29733. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29734. if (depth === void 0) { depth = 1; }
  29735. this.width = width;
  29736. this.height = height;
  29737. this.depth = depth;
  29738. this.baseWidth = width;
  29739. this.baseHeight = height;
  29740. this.baseDepth = depth;
  29741. this._size = width * height * depth;
  29742. };
  29743. /** @hidden */
  29744. InternalTexture.prototype._rebuild = function () {
  29745. var _this = this;
  29746. var proxy;
  29747. this.isReady = false;
  29748. this._cachedCoordinatesMode = null;
  29749. this._cachedWrapU = null;
  29750. this._cachedWrapV = null;
  29751. this._cachedAnisotropicFilteringLevel = null;
  29752. switch (this._dataSource) {
  29753. case InternalTexture.DATASOURCE_TEMP:
  29754. return;
  29755. case InternalTexture.DATASOURCE_URL:
  29756. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29757. _this.isReady = true;
  29758. }, null, this._buffer, undefined, this.format);
  29759. proxy._swapAndDie(this);
  29760. return;
  29761. case InternalTexture.DATASOURCE_RAW:
  29762. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29763. proxy._swapAndDie(this);
  29764. this.isReady = true;
  29765. return;
  29766. case InternalTexture.DATASOURCE_RAW3D:
  29767. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29768. proxy._swapAndDie(this);
  29769. this.isReady = true;
  29770. return;
  29771. case InternalTexture.DATASOURCE_DYNAMIC:
  29772. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29773. proxy._swapAndDie(this);
  29774. // The engine will make sure to update content so no need to flag it as isReady = true
  29775. return;
  29776. case InternalTexture.DATASOURCE_RENDERTARGET:
  29777. var options = new BABYLON.RenderTargetCreationOptions();
  29778. options.generateDepthBuffer = this._generateDepthBuffer;
  29779. options.generateMipMaps = this.generateMipMaps;
  29780. options.generateStencilBuffer = this._generateStencilBuffer;
  29781. options.samplingMode = this.samplingMode;
  29782. options.type = this.type;
  29783. if (this.isCube) {
  29784. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29785. }
  29786. else {
  29787. var size = {
  29788. width: this.width,
  29789. height: this.height
  29790. };
  29791. proxy = this._engine.createRenderTargetTexture(size, options);
  29792. }
  29793. proxy._swapAndDie(this);
  29794. this.isReady = true;
  29795. return;
  29796. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29797. var depthTextureOptions = {
  29798. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29799. comparisonFunction: this._comparisonFunction,
  29800. generateStencil: this._generateStencilBuffer,
  29801. isCube: this.isCube
  29802. };
  29803. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29804. proxy._swapAndDie(this);
  29805. this.isReady = true;
  29806. return;
  29807. case InternalTexture.DATASOURCE_CUBE:
  29808. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29809. _this.isReady = true;
  29810. }, null, this.format, this._extension);
  29811. proxy._swapAndDie(this);
  29812. return;
  29813. case InternalTexture.DATASOURCE_CUBERAW:
  29814. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29815. proxy._swapAndDie(this);
  29816. this.isReady = true;
  29817. return;
  29818. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29819. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29820. if (proxy) {
  29821. proxy._swapAndDie(_this);
  29822. }
  29823. _this.isReady = true;
  29824. }, null, this.format, this._extension);
  29825. return;
  29826. }
  29827. };
  29828. InternalTexture.prototype._swapAndDie = function (target) {
  29829. target._webGLTexture = this._webGLTexture;
  29830. if (this._framebuffer) {
  29831. target._framebuffer = this._framebuffer;
  29832. }
  29833. if (this._depthStencilBuffer) {
  29834. target._depthStencilBuffer = this._depthStencilBuffer;
  29835. }
  29836. if (this._lodTextureHigh) {
  29837. if (target._lodTextureHigh) {
  29838. target._lodTextureHigh.dispose();
  29839. }
  29840. target._lodTextureHigh = this._lodTextureHigh;
  29841. }
  29842. if (this._lodTextureMid) {
  29843. if (target._lodTextureMid) {
  29844. target._lodTextureMid.dispose();
  29845. }
  29846. target._lodTextureMid = this._lodTextureMid;
  29847. }
  29848. if (this._lodTextureLow) {
  29849. if (target._lodTextureLow) {
  29850. target._lodTextureLow.dispose();
  29851. }
  29852. target._lodTextureLow = this._lodTextureLow;
  29853. }
  29854. var cache = this._engine.getLoadedTexturesCache();
  29855. var index = cache.indexOf(this);
  29856. if (index !== -1) {
  29857. cache.splice(index, 1);
  29858. }
  29859. };
  29860. /**
  29861. * Dispose the current allocated resources
  29862. */
  29863. InternalTexture.prototype.dispose = function () {
  29864. if (!this._webGLTexture) {
  29865. return;
  29866. }
  29867. this._references--;
  29868. if (this._references === 0) {
  29869. this._engine._releaseTexture(this);
  29870. this._webGLTexture = null;
  29871. this.previous = null;
  29872. this.next = null;
  29873. }
  29874. };
  29875. /**
  29876. * The source of the texture data is unknown
  29877. */
  29878. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29879. /**
  29880. * Texture data comes from an URL
  29881. */
  29882. InternalTexture.DATASOURCE_URL = 1;
  29883. /**
  29884. * Texture data is only used for temporary storage
  29885. */
  29886. InternalTexture.DATASOURCE_TEMP = 2;
  29887. /**
  29888. * Texture data comes from raw data (ArrayBuffer)
  29889. */
  29890. InternalTexture.DATASOURCE_RAW = 3;
  29891. /**
  29892. * Texture content is dynamic (video or dynamic texture)
  29893. */
  29894. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29895. /**
  29896. * Texture content is generated by rendering to it
  29897. */
  29898. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29899. /**
  29900. * Texture content is part of a multi render target process
  29901. */
  29902. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29903. /**
  29904. * Texture data comes from a cube data file
  29905. */
  29906. InternalTexture.DATASOURCE_CUBE = 7;
  29907. /**
  29908. * Texture data comes from a raw cube data
  29909. */
  29910. InternalTexture.DATASOURCE_CUBERAW = 8;
  29911. /**
  29912. * Texture data come from a prefiltered cube data file
  29913. */
  29914. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29915. /**
  29916. * Texture content is raw 3D data
  29917. */
  29918. InternalTexture.DATASOURCE_RAW3D = 10;
  29919. /**
  29920. * Texture content is a depth texture
  29921. */
  29922. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29923. return InternalTexture;
  29924. }());
  29925. BABYLON.InternalTexture = InternalTexture;
  29926. })(BABYLON || (BABYLON = {}));
  29927. //# sourceMappingURL=babylon.internalTexture.js.map
  29928. var BABYLON;
  29929. (function (BABYLON) {
  29930. var BaseTexture = /** @class */ (function () {
  29931. function BaseTexture(scene) {
  29932. this._hasAlpha = false;
  29933. this.getAlphaFromRGB = false;
  29934. this.level = 1;
  29935. this.coordinatesIndex = 0;
  29936. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29937. /**
  29938. * | Value | Type | Description |
  29939. * | ----- | ------------------ | ----------- |
  29940. * | 0 | CLAMP_ADDRESSMODE | |
  29941. * | 1 | WRAP_ADDRESSMODE | |
  29942. * | 2 | MIRROR_ADDRESSMODE | |
  29943. */
  29944. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29945. /**
  29946. * | Value | Type | Description |
  29947. * | ----- | ------------------ | ----------- |
  29948. * | 0 | CLAMP_ADDRESSMODE | |
  29949. * | 1 | WRAP_ADDRESSMODE | |
  29950. * | 2 | MIRROR_ADDRESSMODE | |
  29951. */
  29952. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29953. /**
  29954. * | Value | Type | Description |
  29955. * | ----- | ------------------ | ----------- |
  29956. * | 0 | CLAMP_ADDRESSMODE | |
  29957. * | 1 | WRAP_ADDRESSMODE | |
  29958. * | 2 | MIRROR_ADDRESSMODE | |
  29959. */
  29960. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29961. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29962. this.isCube = false;
  29963. this.is3D = false;
  29964. this.gammaSpace = true;
  29965. this.invertZ = false;
  29966. this.lodLevelInAlpha = false;
  29967. this.lodGenerationOffset = 0.0;
  29968. this.lodGenerationScale = 0.8;
  29969. this.isRenderTarget = false;
  29970. this.animations = new Array();
  29971. /**
  29972. * An event triggered when the texture is disposed.
  29973. */
  29974. this.onDisposeObservable = new BABYLON.Observable();
  29975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29976. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29977. if (this._scene) {
  29978. this._scene.textures.push(this);
  29979. }
  29980. this._uid = null;
  29981. }
  29982. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29983. get: function () {
  29984. return this._hasAlpha;
  29985. },
  29986. set: function (value) {
  29987. if (this._hasAlpha === value) {
  29988. return;
  29989. }
  29990. this._hasAlpha = value;
  29991. if (this._scene) {
  29992. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29993. }
  29994. },
  29995. enumerable: true,
  29996. configurable: true
  29997. });
  29998. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29999. get: function () {
  30000. return this._coordinatesMode;
  30001. },
  30002. /**
  30003. * How a texture is mapped.
  30004. *
  30005. * | Value | Type | Description |
  30006. * | ----- | ----------------------------------- | ----------- |
  30007. * | 0 | EXPLICIT_MODE | |
  30008. * | 1 | SPHERICAL_MODE | |
  30009. * | 2 | PLANAR_MODE | |
  30010. * | 3 | CUBIC_MODE | |
  30011. * | 4 | PROJECTION_MODE | |
  30012. * | 5 | SKYBOX_MODE | |
  30013. * | 6 | INVCUBIC_MODE | |
  30014. * | 7 | EQUIRECTANGULAR_MODE | |
  30015. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30016. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30017. */
  30018. set: function (value) {
  30019. if (this._coordinatesMode === value) {
  30020. return;
  30021. }
  30022. this._coordinatesMode = value;
  30023. if (this._scene) {
  30024. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30025. }
  30026. },
  30027. enumerable: true,
  30028. configurable: true
  30029. });
  30030. Object.defineProperty(BaseTexture.prototype, "uid", {
  30031. get: function () {
  30032. if (!this._uid) {
  30033. this._uid = BABYLON.Tools.RandomId();
  30034. }
  30035. return this._uid;
  30036. },
  30037. enumerable: true,
  30038. configurable: true
  30039. });
  30040. BaseTexture.prototype.toString = function () {
  30041. return this.name;
  30042. };
  30043. BaseTexture.prototype.getClassName = function () {
  30044. return "BaseTexture";
  30045. };
  30046. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30047. set: function (callback) {
  30048. if (this._onDisposeObserver) {
  30049. this.onDisposeObservable.remove(this._onDisposeObserver);
  30050. }
  30051. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30052. },
  30053. enumerable: true,
  30054. configurable: true
  30055. });
  30056. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30057. get: function () {
  30058. return true;
  30059. },
  30060. enumerable: true,
  30061. configurable: true
  30062. });
  30063. BaseTexture.prototype.getScene = function () {
  30064. return this._scene;
  30065. };
  30066. BaseTexture.prototype.getTextureMatrix = function () {
  30067. return BABYLON.Matrix.IdentityReadOnly;
  30068. };
  30069. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30070. return BABYLON.Matrix.IdentityReadOnly;
  30071. };
  30072. BaseTexture.prototype.getInternalTexture = function () {
  30073. return this._texture;
  30074. };
  30075. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30076. return !this.isBlocking || this.isReady();
  30077. };
  30078. BaseTexture.prototype.isReady = function () {
  30079. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30080. this.delayLoad();
  30081. return false;
  30082. }
  30083. if (this._texture) {
  30084. return this._texture.isReady;
  30085. }
  30086. return false;
  30087. };
  30088. BaseTexture.prototype.getSize = function () {
  30089. if (this._texture && this._texture.width) {
  30090. return new BABYLON.Size(this._texture.width, this._texture.height);
  30091. }
  30092. if (this._texture && this._texture._size) {
  30093. return new BABYLON.Size(this._texture._size, this._texture._size);
  30094. }
  30095. return BABYLON.Size.Zero();
  30096. };
  30097. BaseTexture.prototype.getBaseSize = function () {
  30098. if (!this.isReady() || !this._texture)
  30099. return BABYLON.Size.Zero();
  30100. if (this._texture._size) {
  30101. return new BABYLON.Size(this._texture._size, this._texture._size);
  30102. }
  30103. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30104. };
  30105. BaseTexture.prototype.scale = function (ratio) {
  30106. };
  30107. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30108. get: function () {
  30109. return false;
  30110. },
  30111. enumerable: true,
  30112. configurable: true
  30113. });
  30114. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30115. if (!this._scene) {
  30116. return null;
  30117. }
  30118. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30119. for (var index = 0; index < texturesCache.length; index++) {
  30120. var texturesCacheEntry = texturesCache[index];
  30121. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30122. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30123. texturesCacheEntry.incrementReferences();
  30124. return texturesCacheEntry;
  30125. }
  30126. }
  30127. }
  30128. return null;
  30129. };
  30130. BaseTexture.prototype._rebuild = function () {
  30131. };
  30132. BaseTexture.prototype.delayLoad = function () {
  30133. };
  30134. BaseTexture.prototype.clone = function () {
  30135. return null;
  30136. };
  30137. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30138. get: function () {
  30139. if (!this._texture) {
  30140. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30141. }
  30142. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30143. },
  30144. enumerable: true,
  30145. configurable: true
  30146. });
  30147. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30148. get: function () {
  30149. if (!this._texture) {
  30150. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30151. }
  30152. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30153. },
  30154. enumerable: true,
  30155. configurable: true
  30156. });
  30157. BaseTexture.prototype.readPixels = function (faceIndex) {
  30158. if (faceIndex === void 0) { faceIndex = 0; }
  30159. if (!this._texture) {
  30160. return null;
  30161. }
  30162. var size = this.getSize();
  30163. var scene = this.getScene();
  30164. if (!scene) {
  30165. return null;
  30166. }
  30167. var engine = scene.getEngine();
  30168. if (this._texture.isCube) {
  30169. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30170. }
  30171. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30172. };
  30173. BaseTexture.prototype.releaseInternalTexture = function () {
  30174. if (this._texture) {
  30175. this._texture.dispose();
  30176. this._texture = null;
  30177. }
  30178. };
  30179. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30180. get: function () {
  30181. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30182. return null;
  30183. }
  30184. if (!this._texture._sphericalPolynomial) {
  30185. this._texture._sphericalPolynomial =
  30186. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30187. }
  30188. return this._texture._sphericalPolynomial;
  30189. },
  30190. set: function (value) {
  30191. if (this._texture) {
  30192. this._texture._sphericalPolynomial = value;
  30193. }
  30194. },
  30195. enumerable: true,
  30196. configurable: true
  30197. });
  30198. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30199. get: function () {
  30200. if (this._texture) {
  30201. return this._texture._lodTextureHigh;
  30202. }
  30203. return null;
  30204. },
  30205. enumerable: true,
  30206. configurable: true
  30207. });
  30208. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30209. get: function () {
  30210. if (this._texture) {
  30211. return this._texture._lodTextureMid;
  30212. }
  30213. return null;
  30214. },
  30215. enumerable: true,
  30216. configurable: true
  30217. });
  30218. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30219. get: function () {
  30220. if (this._texture) {
  30221. return this._texture._lodTextureLow;
  30222. }
  30223. return null;
  30224. },
  30225. enumerable: true,
  30226. configurable: true
  30227. });
  30228. BaseTexture.prototype.dispose = function () {
  30229. if (!this._scene) {
  30230. return;
  30231. }
  30232. // Animations
  30233. this._scene.stopAnimation(this);
  30234. // Remove from scene
  30235. this._scene._removePendingData(this);
  30236. var index = this._scene.textures.indexOf(this);
  30237. if (index >= 0) {
  30238. this._scene.textures.splice(index, 1);
  30239. }
  30240. if (this._texture === undefined) {
  30241. return;
  30242. }
  30243. // Release
  30244. this.releaseInternalTexture();
  30245. // Callback
  30246. this.onDisposeObservable.notifyObservers(this);
  30247. this.onDisposeObservable.clear();
  30248. };
  30249. BaseTexture.prototype.serialize = function () {
  30250. if (!this.name) {
  30251. return null;
  30252. }
  30253. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30254. // Animations
  30255. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30256. return serializationObject;
  30257. };
  30258. BaseTexture.WhenAllReady = function (textures, callback) {
  30259. var numRemaining = textures.length;
  30260. if (numRemaining === 0) {
  30261. callback();
  30262. return;
  30263. }
  30264. var _loop_1 = function () {
  30265. texture = textures[i];
  30266. if (texture.isReady()) {
  30267. if (--numRemaining === 0) {
  30268. callback();
  30269. }
  30270. }
  30271. else {
  30272. onLoadObservable = texture.onLoadObservable;
  30273. var onLoadCallback_1 = function () {
  30274. onLoadObservable.removeCallback(onLoadCallback_1);
  30275. if (--numRemaining === 0) {
  30276. callback();
  30277. }
  30278. };
  30279. onLoadObservable.add(onLoadCallback_1);
  30280. }
  30281. };
  30282. var texture, onLoadObservable;
  30283. for (var i = 0; i < textures.length; i++) {
  30284. _loop_1();
  30285. }
  30286. };
  30287. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30288. __decorate([
  30289. BABYLON.serialize()
  30290. ], BaseTexture.prototype, "name", void 0);
  30291. __decorate([
  30292. BABYLON.serialize("hasAlpha")
  30293. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30294. __decorate([
  30295. BABYLON.serialize()
  30296. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30297. __decorate([
  30298. BABYLON.serialize()
  30299. ], BaseTexture.prototype, "level", void 0);
  30300. __decorate([
  30301. BABYLON.serialize()
  30302. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30303. __decorate([
  30304. BABYLON.serialize("coordinatesMode")
  30305. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30306. __decorate([
  30307. BABYLON.serialize()
  30308. ], BaseTexture.prototype, "wrapU", void 0);
  30309. __decorate([
  30310. BABYLON.serialize()
  30311. ], BaseTexture.prototype, "wrapV", void 0);
  30312. __decorate([
  30313. BABYLON.serialize()
  30314. ], BaseTexture.prototype, "wrapR", void 0);
  30315. __decorate([
  30316. BABYLON.serialize()
  30317. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30318. __decorate([
  30319. BABYLON.serialize()
  30320. ], BaseTexture.prototype, "isCube", void 0);
  30321. __decorate([
  30322. BABYLON.serialize()
  30323. ], BaseTexture.prototype, "is3D", void 0);
  30324. __decorate([
  30325. BABYLON.serialize()
  30326. ], BaseTexture.prototype, "gammaSpace", void 0);
  30327. __decorate([
  30328. BABYLON.serialize()
  30329. ], BaseTexture.prototype, "invertZ", void 0);
  30330. __decorate([
  30331. BABYLON.serialize()
  30332. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30333. __decorate([
  30334. BABYLON.serialize()
  30335. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30336. __decorate([
  30337. BABYLON.serialize()
  30338. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30339. __decorate([
  30340. BABYLON.serialize()
  30341. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30342. return BaseTexture;
  30343. }());
  30344. BABYLON.BaseTexture = BaseTexture;
  30345. })(BABYLON || (BABYLON = {}));
  30346. //# sourceMappingURL=babylon.baseTexture.js.map
  30347. var BABYLON;
  30348. (function (BABYLON) {
  30349. var Texture = /** @class */ (function (_super) {
  30350. __extends(Texture, _super);
  30351. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30352. if (noMipmap === void 0) { noMipmap = false; }
  30353. if (invertY === void 0) { invertY = true; }
  30354. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30355. if (onLoad === void 0) { onLoad = null; }
  30356. if (onError === void 0) { onError = null; }
  30357. if (buffer === void 0) { buffer = null; }
  30358. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30359. var _this = _super.call(this, scene) || this;
  30360. _this.uOffset = 0;
  30361. _this.vOffset = 0;
  30362. _this.uScale = 1.0;
  30363. _this.vScale = 1.0;
  30364. _this.uAng = 0;
  30365. _this.vAng = 0;
  30366. _this.wAng = 0;
  30367. _this._isBlocking = true;
  30368. _this.name = url || "";
  30369. _this.url = url;
  30370. _this._noMipmap = noMipmap;
  30371. _this._invertY = invertY;
  30372. _this._samplingMode = samplingMode;
  30373. _this._buffer = buffer;
  30374. _this._deleteBuffer = deleteBuffer;
  30375. if (format) {
  30376. _this._format = format;
  30377. }
  30378. scene = _this.getScene();
  30379. if (!scene) {
  30380. return _this;
  30381. }
  30382. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30383. var load = function () {
  30384. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30385. _this.onLoadObservable.notifyObservers(_this);
  30386. }
  30387. if (onLoad) {
  30388. onLoad();
  30389. }
  30390. if (!_this.isBlocking && scene) {
  30391. scene.resetCachedMaterial();
  30392. }
  30393. };
  30394. if (!_this.url) {
  30395. _this._delayedOnLoad = load;
  30396. _this._delayedOnError = onError;
  30397. return _this;
  30398. }
  30399. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30400. if (!_this._texture) {
  30401. if (!scene.useDelayedTextureLoading) {
  30402. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30403. if (deleteBuffer) {
  30404. delete _this._buffer;
  30405. }
  30406. }
  30407. else {
  30408. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30409. _this._delayedOnLoad = load;
  30410. _this._delayedOnError = onError;
  30411. }
  30412. }
  30413. else {
  30414. if (_this._texture.isReady) {
  30415. BABYLON.Tools.SetImmediate(function () { return load(); });
  30416. }
  30417. else {
  30418. _this._texture.onLoadedObservable.add(load);
  30419. }
  30420. }
  30421. return _this;
  30422. }
  30423. Object.defineProperty(Texture.prototype, "noMipmap", {
  30424. get: function () {
  30425. return this._noMipmap;
  30426. },
  30427. enumerable: true,
  30428. configurable: true
  30429. });
  30430. Object.defineProperty(Texture.prototype, "isBlocking", {
  30431. get: function () {
  30432. return this._isBlocking;
  30433. },
  30434. set: function (value) {
  30435. this._isBlocking = value;
  30436. },
  30437. enumerable: true,
  30438. configurable: true
  30439. });
  30440. Object.defineProperty(Texture.prototype, "samplingMode", {
  30441. get: function () {
  30442. return this._samplingMode;
  30443. },
  30444. enumerable: true,
  30445. configurable: true
  30446. });
  30447. Texture.prototype.updateURL = function (url) {
  30448. this.url = url;
  30449. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30450. this.delayLoad();
  30451. };
  30452. Texture.prototype.delayLoad = function () {
  30453. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30454. return;
  30455. }
  30456. var scene = this.getScene();
  30457. if (!scene) {
  30458. return;
  30459. }
  30460. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30461. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30462. if (!this._texture) {
  30463. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30464. if (this._deleteBuffer) {
  30465. delete this._buffer;
  30466. }
  30467. }
  30468. else {
  30469. if (this._delayedOnLoad) {
  30470. if (this._texture.isReady) {
  30471. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30472. }
  30473. else {
  30474. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30475. }
  30476. }
  30477. }
  30478. this._delayedOnLoad = null;
  30479. this._delayedOnError = null;
  30480. };
  30481. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30482. if (!this._texture) {
  30483. return;
  30484. }
  30485. var scene = this.getScene();
  30486. if (!scene) {
  30487. return;
  30488. }
  30489. this._samplingMode = samplingMode;
  30490. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30491. };
  30492. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30493. x *= this.uScale;
  30494. y *= this.vScale;
  30495. x -= 0.5 * this.uScale;
  30496. y -= 0.5 * this.vScale;
  30497. z -= 0.5;
  30498. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30499. t.x += 0.5 * this.uScale + this.uOffset;
  30500. t.y += 0.5 * this.vScale + this.vOffset;
  30501. t.z += 0.5;
  30502. };
  30503. Texture.prototype.getTextureMatrix = function () {
  30504. var _this = this;
  30505. if (this.uOffset === this._cachedUOffset &&
  30506. this.vOffset === this._cachedVOffset &&
  30507. this.uScale === this._cachedUScale &&
  30508. this.vScale === this._cachedVScale &&
  30509. this.uAng === this._cachedUAng &&
  30510. this.vAng === this._cachedVAng &&
  30511. this.wAng === this._cachedWAng) {
  30512. return this._cachedTextureMatrix;
  30513. }
  30514. this._cachedUOffset = this.uOffset;
  30515. this._cachedVOffset = this.vOffset;
  30516. this._cachedUScale = this.uScale;
  30517. this._cachedVScale = this.vScale;
  30518. this._cachedUAng = this.uAng;
  30519. this._cachedVAng = this.vAng;
  30520. this._cachedWAng = this.wAng;
  30521. if (!this._cachedTextureMatrix) {
  30522. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30523. this._rowGenerationMatrix = new BABYLON.Matrix();
  30524. this._t0 = BABYLON.Vector3.Zero();
  30525. this._t1 = BABYLON.Vector3.Zero();
  30526. this._t2 = BABYLON.Vector3.Zero();
  30527. }
  30528. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30529. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30530. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30531. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30532. this._t1.subtractInPlace(this._t0);
  30533. this._t2.subtractInPlace(this._t0);
  30534. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30535. this._cachedTextureMatrix.m[0] = this._t1.x;
  30536. this._cachedTextureMatrix.m[1] = this._t1.y;
  30537. this._cachedTextureMatrix.m[2] = this._t1.z;
  30538. this._cachedTextureMatrix.m[4] = this._t2.x;
  30539. this._cachedTextureMatrix.m[5] = this._t2.y;
  30540. this._cachedTextureMatrix.m[6] = this._t2.z;
  30541. this._cachedTextureMatrix.m[8] = this._t0.x;
  30542. this._cachedTextureMatrix.m[9] = this._t0.y;
  30543. this._cachedTextureMatrix.m[10] = this._t0.z;
  30544. var scene = this.getScene();
  30545. if (!scene) {
  30546. return this._cachedTextureMatrix;
  30547. }
  30548. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30549. return mat.hasTexture(_this);
  30550. });
  30551. return this._cachedTextureMatrix;
  30552. };
  30553. Texture.prototype.getReflectionTextureMatrix = function () {
  30554. var _this = this;
  30555. var scene = this.getScene();
  30556. if (!scene) {
  30557. return this._cachedTextureMatrix;
  30558. }
  30559. if (this.uOffset === this._cachedUOffset &&
  30560. this.vOffset === this._cachedVOffset &&
  30561. this.uScale === this._cachedUScale &&
  30562. this.vScale === this._cachedVScale &&
  30563. this.coordinatesMode === this._cachedCoordinatesMode) {
  30564. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30565. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30566. return this._cachedTextureMatrix;
  30567. }
  30568. }
  30569. else {
  30570. return this._cachedTextureMatrix;
  30571. }
  30572. }
  30573. if (!this._cachedTextureMatrix) {
  30574. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30575. }
  30576. if (!this._projectionModeMatrix) {
  30577. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30578. }
  30579. this._cachedUOffset = this.uOffset;
  30580. this._cachedVOffset = this.vOffset;
  30581. this._cachedUScale = this.uScale;
  30582. this._cachedVScale = this.vScale;
  30583. this._cachedCoordinatesMode = this.coordinatesMode;
  30584. switch (this.coordinatesMode) {
  30585. case Texture.PLANAR_MODE:
  30586. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30587. this._cachedTextureMatrix[0] = this.uScale;
  30588. this._cachedTextureMatrix[5] = this.vScale;
  30589. this._cachedTextureMatrix[12] = this.uOffset;
  30590. this._cachedTextureMatrix[13] = this.vOffset;
  30591. break;
  30592. case Texture.PROJECTION_MODE:
  30593. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30594. this._projectionModeMatrix.m[0] = 0.5;
  30595. this._projectionModeMatrix.m[5] = -0.5;
  30596. this._projectionModeMatrix.m[10] = 0.0;
  30597. this._projectionModeMatrix.m[12] = 0.5;
  30598. this._projectionModeMatrix.m[13] = 0.5;
  30599. this._projectionModeMatrix.m[14] = 1.0;
  30600. this._projectionModeMatrix.m[15] = 1.0;
  30601. var projectionMatrix = scene.getProjectionMatrix();
  30602. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30603. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30604. break;
  30605. default:
  30606. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30607. break;
  30608. }
  30609. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30610. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30611. });
  30612. return this._cachedTextureMatrix;
  30613. };
  30614. Texture.prototype.clone = function () {
  30615. var _this = this;
  30616. return BABYLON.SerializationHelper.Clone(function () {
  30617. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30618. }, this);
  30619. };
  30620. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30621. get: function () {
  30622. if (!this._onLoadObservable) {
  30623. this._onLoadObservable = new BABYLON.Observable();
  30624. }
  30625. return this._onLoadObservable;
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. Texture.prototype.serialize = function () {
  30631. var serializationObject = _super.prototype.serialize.call(this);
  30632. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30633. serializationObject.base64String = this._buffer;
  30634. serializationObject.name = serializationObject.name.replace("data:", "");
  30635. }
  30636. serializationObject.invertY = this._invertY;
  30637. serializationObject.samplingMode = this.samplingMode;
  30638. return serializationObject;
  30639. };
  30640. Texture.prototype.getClassName = function () {
  30641. return "Texture";
  30642. };
  30643. Texture.prototype.dispose = function () {
  30644. _super.prototype.dispose.call(this);
  30645. if (this.onLoadObservable) {
  30646. this.onLoadObservable.clear();
  30647. this._onLoadObservable = null;
  30648. }
  30649. this._delayedOnLoad = null;
  30650. this._delayedOnError = null;
  30651. };
  30652. // Statics
  30653. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30654. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30655. if (onLoad === void 0) { onLoad = null; }
  30656. if (onError === void 0) { onError = null; }
  30657. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30658. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30659. };
  30660. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30661. if (parsedTexture.customType) {
  30662. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30663. // Update Sampling Mode
  30664. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30665. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30666. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30667. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30668. }
  30669. }
  30670. return parsedCustomTexture;
  30671. }
  30672. if (parsedTexture.isCube) {
  30673. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30674. }
  30675. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30676. return null;
  30677. }
  30678. var texture = BABYLON.SerializationHelper.Parse(function () {
  30679. var generateMipMaps = true;
  30680. if (parsedTexture.noMipmap) {
  30681. generateMipMaps = false;
  30682. }
  30683. if (parsedTexture.mirrorPlane) {
  30684. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30685. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30686. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30687. return mirrorTexture;
  30688. }
  30689. else if (parsedTexture.isRenderTarget) {
  30690. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30691. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30692. return renderTargetTexture;
  30693. }
  30694. else {
  30695. var texture;
  30696. if (parsedTexture.base64String) {
  30697. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30698. }
  30699. else {
  30700. var url = rootUrl + parsedTexture.name;
  30701. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30702. url = parsedTexture.url;
  30703. }
  30704. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30705. }
  30706. return texture;
  30707. }
  30708. }, parsedTexture, scene);
  30709. // Update Sampling Mode
  30710. if (parsedTexture.samplingMode) {
  30711. var sampling = parsedTexture.samplingMode;
  30712. if (texture._samplingMode !== sampling) {
  30713. texture.updateSamplingMode(sampling);
  30714. }
  30715. }
  30716. // Animations
  30717. if (parsedTexture.animations) {
  30718. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30719. var parsedAnimation = parsedTexture.animations[animationIndex];
  30720. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30721. }
  30722. }
  30723. return texture;
  30724. };
  30725. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30726. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30727. if (noMipmap === void 0) { noMipmap = false; }
  30728. if (invertY === void 0) { invertY = true; }
  30729. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30730. if (onLoad === void 0) { onLoad = null; }
  30731. if (onError === void 0) { onError = null; }
  30732. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30733. if (name.substr(0, 5) !== "data:") {
  30734. name = "data:" + name;
  30735. }
  30736. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30737. };
  30738. // Constants
  30739. Texture.NEAREST_SAMPLINGMODE = 1;
  30740. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30741. Texture.BILINEAR_SAMPLINGMODE = 2;
  30742. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30743. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30744. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30745. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30746. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30747. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30748. Texture.NEAREST_LINEAR = 7;
  30749. Texture.NEAREST_NEAREST = 8;
  30750. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30751. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30752. Texture.LINEAR_LINEAR = 11;
  30753. Texture.LINEAR_NEAREST = 12;
  30754. Texture.EXPLICIT_MODE = 0;
  30755. Texture.SPHERICAL_MODE = 1;
  30756. Texture.PLANAR_MODE = 2;
  30757. Texture.CUBIC_MODE = 3;
  30758. Texture.PROJECTION_MODE = 4;
  30759. Texture.SKYBOX_MODE = 5;
  30760. Texture.INVCUBIC_MODE = 6;
  30761. Texture.EQUIRECTANGULAR_MODE = 7;
  30762. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30763. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30764. Texture.CLAMP_ADDRESSMODE = 0;
  30765. Texture.WRAP_ADDRESSMODE = 1;
  30766. Texture.MIRROR_ADDRESSMODE = 2;
  30767. /**
  30768. * 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
  30769. */
  30770. Texture.UseSerializedUrlIfAny = false;
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], Texture.prototype, "url", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], Texture.prototype, "uOffset", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], Texture.prototype, "vOffset", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], Texture.prototype, "uScale", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], Texture.prototype, "vScale", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], Texture.prototype, "uAng", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], Texture.prototype, "vAng", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], Texture.prototype, "wAng", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], Texture.prototype, "isBlocking", null);
  30798. return Texture;
  30799. }(BABYLON.BaseTexture));
  30800. BABYLON.Texture = Texture;
  30801. })(BABYLON || (BABYLON = {}));
  30802. //# sourceMappingURL=babylon.texture.js.map
  30803. var BABYLON;
  30804. (function (BABYLON) {
  30805. /**
  30806. * @hidden
  30807. **/
  30808. var _InstancesBatch = /** @class */ (function () {
  30809. function _InstancesBatch() {
  30810. this.mustReturn = false;
  30811. this.visibleInstances = new Array();
  30812. this.renderSelf = new Array();
  30813. }
  30814. return _InstancesBatch;
  30815. }());
  30816. BABYLON._InstancesBatch = _InstancesBatch;
  30817. var Mesh = /** @class */ (function (_super) {
  30818. __extends(Mesh, _super);
  30819. /**
  30820. * @constructor
  30821. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30822. * @param {Scene} scene The scene to add this mesh to.
  30823. * @param {Node} parent The parent of this mesh, if it has one
  30824. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30825. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30826. * When false, achieved by calling a clone(), also passing False.
  30827. * This will make creation of children, recursive.
  30828. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30829. */
  30830. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30831. if (scene === void 0) { scene = null; }
  30832. if (parent === void 0) { parent = null; }
  30833. if (source === void 0) { source = null; }
  30834. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30835. var _this = _super.call(this, name, scene) || this;
  30836. // Events
  30837. /**
  30838. * An event triggered before rendering the mesh
  30839. */
  30840. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30841. /**
  30842. * An event triggered after rendering the mesh
  30843. */
  30844. _this.onAfterRenderObservable = new BABYLON.Observable();
  30845. /**
  30846. * An event triggered before drawing the mesh
  30847. */
  30848. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30849. // Members
  30850. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30851. _this.instances = new Array();
  30852. _this._LODLevels = new Array();
  30853. _this._visibleInstances = {};
  30854. _this._renderIdForInstances = new Array();
  30855. _this._batchCache = new _InstancesBatch();
  30856. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30857. // Use by builder only to know what orientation were the mesh build in.
  30858. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30859. _this.overrideMaterialSideOrientation = null;
  30860. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30861. // Will be used to save a source mesh reference, If any
  30862. _this._source = null;
  30863. scene = _this.getScene();
  30864. if (source) {
  30865. // Source mesh
  30866. _this._source = source;
  30867. // Geometry
  30868. if (source._geometry) {
  30869. source._geometry.applyToMesh(_this);
  30870. }
  30871. // Deep copy
  30872. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30873. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30874. // Metadata
  30875. if (source.metadata && source.metadata.clone) {
  30876. _this.metadata = source.metadata.clone();
  30877. }
  30878. else {
  30879. _this.metadata = source.metadata;
  30880. }
  30881. // Tags
  30882. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30883. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30884. }
  30885. // Parent
  30886. _this.parent = source.parent;
  30887. // Pivot
  30888. _this.setPivotMatrix(source.getPivotMatrix());
  30889. _this.id = name + "." + source.id;
  30890. // Material
  30891. _this.material = source.material;
  30892. var index;
  30893. if (!doNotCloneChildren) {
  30894. // Children
  30895. var directDescendants = source.getDescendants(true);
  30896. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30897. var child = directDescendants[index_1];
  30898. if (child.clone) {
  30899. child.clone(name + "." + child.name, _this);
  30900. }
  30901. }
  30902. }
  30903. // Physics clone
  30904. var physicsEngine = _this.getScene().getPhysicsEngine();
  30905. if (clonePhysicsImpostor && physicsEngine) {
  30906. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30907. if (impostor) {
  30908. _this.physicsImpostor = impostor.clone(_this);
  30909. }
  30910. }
  30911. // Particles
  30912. for (index = 0; index < scene.particleSystems.length; index++) {
  30913. var system = scene.particleSystems[index];
  30914. if (system.emitter === source) {
  30915. system.clone(system.name, _this);
  30916. }
  30917. }
  30918. _this.computeWorldMatrix(true);
  30919. }
  30920. // Parent
  30921. if (parent !== null) {
  30922. _this.parent = parent;
  30923. }
  30924. return _this;
  30925. }
  30926. Object.defineProperty(Mesh, "FRONTSIDE", {
  30927. /**
  30928. * Mesh side orientation : usually the external or front surface
  30929. */
  30930. get: function () {
  30931. return Mesh._FRONTSIDE;
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. Object.defineProperty(Mesh, "BACKSIDE", {
  30937. /**
  30938. * Mesh side orientation : usually the internal or back surface
  30939. */
  30940. get: function () {
  30941. return Mesh._BACKSIDE;
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30947. /**
  30948. * Mesh side orientation : both internal and external or front and back surfaces
  30949. */
  30950. get: function () {
  30951. return Mesh._DOUBLESIDE;
  30952. },
  30953. enumerable: true,
  30954. configurable: true
  30955. });
  30956. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30957. /**
  30958. * Mesh side orientation : by default, `FRONTSIDE`
  30959. */
  30960. get: function () {
  30961. return Mesh._DEFAULTSIDE;
  30962. },
  30963. enumerable: true,
  30964. configurable: true
  30965. });
  30966. Object.defineProperty(Mesh, "NO_CAP", {
  30967. /**
  30968. * Mesh cap setting : no cap
  30969. */
  30970. get: function () {
  30971. return Mesh._NO_CAP;
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. Object.defineProperty(Mesh, "CAP_START", {
  30977. /**
  30978. * Mesh cap setting : one cap at the beginning of the mesh
  30979. */
  30980. get: function () {
  30981. return Mesh._CAP_START;
  30982. },
  30983. enumerable: true,
  30984. configurable: true
  30985. });
  30986. Object.defineProperty(Mesh, "CAP_END", {
  30987. /**
  30988. * Mesh cap setting : one cap at the end of the mesh
  30989. */
  30990. get: function () {
  30991. return Mesh._CAP_END;
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. Object.defineProperty(Mesh, "CAP_ALL", {
  30997. /**
  30998. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30999. */
  31000. get: function () {
  31001. return Mesh._CAP_ALL;
  31002. },
  31003. enumerable: true,
  31004. configurable: true
  31005. });
  31006. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31007. set: function (callback) {
  31008. if (this._onBeforeDrawObserver) {
  31009. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31010. }
  31011. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31012. },
  31013. enumerable: true,
  31014. configurable: true
  31015. });
  31016. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31017. get: function () {
  31018. return this._morphTargetManager;
  31019. },
  31020. set: function (value) {
  31021. if (this._morphTargetManager === value) {
  31022. return;
  31023. }
  31024. this._morphTargetManager = value;
  31025. this._syncGeometryWithMorphTargetManager();
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Mesh.prototype, "source", {
  31031. get: function () {
  31032. return this._source;
  31033. },
  31034. enumerable: true,
  31035. configurable: true
  31036. });
  31037. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31038. get: function () {
  31039. return this._unIndexed;
  31040. },
  31041. set: function (value) {
  31042. if (this._unIndexed !== value) {
  31043. this._unIndexed = value;
  31044. this._markSubMeshesAsAttributesDirty();
  31045. }
  31046. },
  31047. enumerable: true,
  31048. configurable: true
  31049. });
  31050. // Methods
  31051. /**
  31052. * Returns the string "Mesh".
  31053. */
  31054. Mesh.prototype.getClassName = function () {
  31055. return "Mesh";
  31056. };
  31057. /**
  31058. * Returns a string.
  31059. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31060. */
  31061. Mesh.prototype.toString = function (fullDetails) {
  31062. var ret = _super.prototype.toString.call(this, fullDetails);
  31063. ret += ", n vertices: " + this.getTotalVertices();
  31064. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31065. if (this.animations) {
  31066. for (var i = 0; i < this.animations.length; i++) {
  31067. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31068. }
  31069. }
  31070. if (fullDetails) {
  31071. if (this._geometry) {
  31072. var ib = this.getIndices();
  31073. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31074. if (vb && ib) {
  31075. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31076. }
  31077. }
  31078. else {
  31079. ret += ", flat shading: UNKNOWN";
  31080. }
  31081. }
  31082. return ret;
  31083. };
  31084. Mesh.prototype._unBindEffect = function () {
  31085. _super.prototype._unBindEffect.call(this);
  31086. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31087. var instance = _a[_i];
  31088. instance._unBindEffect();
  31089. }
  31090. };
  31091. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31092. /**
  31093. * True if the mesh has some Levels Of Details (LOD).
  31094. * Returns a boolean.
  31095. */
  31096. get: function () {
  31097. return this._LODLevels.length > 0;
  31098. },
  31099. enumerable: true,
  31100. configurable: true
  31101. });
  31102. /**
  31103. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31104. * @returns an array of {BABYLON.MeshLODLevel}
  31105. */
  31106. Mesh.prototype.getLODLevels = function () {
  31107. return this._LODLevels;
  31108. };
  31109. Mesh.prototype._sortLODLevels = function () {
  31110. this._LODLevels.sort(function (a, b) {
  31111. if (a.distance < b.distance) {
  31112. return 1;
  31113. }
  31114. if (a.distance > b.distance) {
  31115. return -1;
  31116. }
  31117. return 0;
  31118. });
  31119. };
  31120. /**
  31121. * Add a mesh as LOD level triggered at the given distance.
  31122. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31123. * @param {number} distance The distance from the center of the object to show this level
  31124. * @param {Mesh} mesh The mesh to be added as LOD level
  31125. * @return {Mesh} This mesh (for chaining)
  31126. */
  31127. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31128. if (mesh && mesh._masterMesh) {
  31129. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31130. return this;
  31131. }
  31132. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31133. this._LODLevels.push(level);
  31134. if (mesh) {
  31135. mesh._masterMesh = this;
  31136. }
  31137. this._sortLODLevels();
  31138. return this;
  31139. };
  31140. /**
  31141. * Returns the LOD level mesh at the passed distance or null if not found.
  31142. * It is related to the method `addLODLevel(distance, mesh)`.
  31143. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31144. * Returns an object Mesh or `null`.
  31145. */
  31146. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31147. for (var index = 0; index < this._LODLevels.length; index++) {
  31148. var level = this._LODLevels[index];
  31149. if (level.distance === distance) {
  31150. return level.mesh;
  31151. }
  31152. }
  31153. return null;
  31154. };
  31155. /**
  31156. * Remove a mesh from the LOD array
  31157. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31158. * @param {Mesh} mesh The mesh to be removed.
  31159. * @return {Mesh} This mesh (for chaining)
  31160. */
  31161. Mesh.prototype.removeLODLevel = function (mesh) {
  31162. for (var index = 0; index < this._LODLevels.length; index++) {
  31163. if (this._LODLevels[index].mesh === mesh) {
  31164. this._LODLevels.splice(index, 1);
  31165. if (mesh) {
  31166. mesh._masterMesh = null;
  31167. }
  31168. }
  31169. }
  31170. this._sortLODLevels();
  31171. return this;
  31172. };
  31173. /**
  31174. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31175. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31176. */
  31177. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31178. if (!this._LODLevels || this._LODLevels.length === 0) {
  31179. return this;
  31180. }
  31181. var bSphere;
  31182. if (boundingSphere) {
  31183. bSphere = boundingSphere;
  31184. }
  31185. else {
  31186. var boundingInfo = this.getBoundingInfo();
  31187. bSphere = boundingInfo.boundingSphere;
  31188. }
  31189. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31190. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31191. if (this.onLODLevelSelection) {
  31192. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31193. }
  31194. return this;
  31195. }
  31196. for (var index = 0; index < this._LODLevels.length; index++) {
  31197. var level = this._LODLevels[index];
  31198. if (level.distance < distanceToCamera) {
  31199. if (level.mesh) {
  31200. level.mesh._preActivate();
  31201. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31202. }
  31203. if (this.onLODLevelSelection) {
  31204. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31205. }
  31206. return level.mesh;
  31207. }
  31208. }
  31209. if (this.onLODLevelSelection) {
  31210. this.onLODLevelSelection(distanceToCamera, this, this);
  31211. }
  31212. return this;
  31213. };
  31214. Object.defineProperty(Mesh.prototype, "geometry", {
  31215. /**
  31216. * Returns the mesh internal Geometry object.
  31217. */
  31218. get: function () {
  31219. return this._geometry;
  31220. },
  31221. enumerable: true,
  31222. configurable: true
  31223. });
  31224. /**
  31225. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31226. */
  31227. Mesh.prototype.getTotalVertices = function () {
  31228. if (this._geometry === null || this._geometry === undefined) {
  31229. return 0;
  31230. }
  31231. return this._geometry.getTotalVertices();
  31232. };
  31233. /**
  31234. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31235. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31236. * You can force the copy with forceCopy === true
  31237. * Returns null if the mesh has no geometry or no vertex buffer.
  31238. * Possible `kind` values :
  31239. * - BABYLON.VertexBuffer.PositionKind
  31240. * - BABYLON.VertexBuffer.UVKind
  31241. * - BABYLON.VertexBuffer.UV2Kind
  31242. * - BABYLON.VertexBuffer.UV3Kind
  31243. * - BABYLON.VertexBuffer.UV4Kind
  31244. * - BABYLON.VertexBuffer.UV5Kind
  31245. * - BABYLON.VertexBuffer.UV6Kind
  31246. * - BABYLON.VertexBuffer.ColorKind
  31247. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31248. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31249. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31250. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31251. */
  31252. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31253. if (!this._geometry) {
  31254. return null;
  31255. }
  31256. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31257. };
  31258. /**
  31259. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31260. * Returns `null` if the mesh has no geometry.
  31261. * Possible `kind` values :
  31262. * - BABYLON.VertexBuffer.PositionKind
  31263. * - BABYLON.VertexBuffer.UVKind
  31264. * - BABYLON.VertexBuffer.UV2Kind
  31265. * - BABYLON.VertexBuffer.UV3Kind
  31266. * - BABYLON.VertexBuffer.UV4Kind
  31267. * - BABYLON.VertexBuffer.UV5Kind
  31268. * - BABYLON.VertexBuffer.UV6Kind
  31269. * - BABYLON.VertexBuffer.ColorKind
  31270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31274. */
  31275. Mesh.prototype.getVertexBuffer = function (kind) {
  31276. if (!this._geometry) {
  31277. return null;
  31278. }
  31279. return this._geometry.getVertexBuffer(kind);
  31280. };
  31281. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31282. if (!this._geometry) {
  31283. if (this._delayInfo) {
  31284. return this._delayInfo.indexOf(kind) !== -1;
  31285. }
  31286. return false;
  31287. }
  31288. return this._geometry.isVerticesDataPresent(kind);
  31289. };
  31290. /**
  31291. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31292. * Possible `kind` values :
  31293. * - BABYLON.VertexBuffer.PositionKind
  31294. * - BABYLON.VertexBuffer.UVKind
  31295. * - BABYLON.VertexBuffer.UV2Kind
  31296. * - BABYLON.VertexBuffer.UV3Kind
  31297. * - BABYLON.VertexBuffer.UV4Kind
  31298. * - BABYLON.VertexBuffer.UV5Kind
  31299. * - BABYLON.VertexBuffer.UV6Kind
  31300. * - BABYLON.VertexBuffer.ColorKind
  31301. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31302. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31303. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31304. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31305. */
  31306. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31307. if (!this._geometry) {
  31308. if (this._delayInfo) {
  31309. return this._delayInfo.indexOf(kind) !== -1;
  31310. }
  31311. return false;
  31312. }
  31313. return this._geometry.isVertexBufferUpdatable(kind);
  31314. };
  31315. /**
  31316. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31317. * Possible `kind` values :
  31318. * - BABYLON.VertexBuffer.PositionKind
  31319. * - BABYLON.VertexBuffer.UVKind
  31320. * - BABYLON.VertexBuffer.UV2Kind
  31321. * - BABYLON.VertexBuffer.UV3Kind
  31322. * - BABYLON.VertexBuffer.UV4Kind
  31323. * - BABYLON.VertexBuffer.UV5Kind
  31324. * - BABYLON.VertexBuffer.UV6Kind
  31325. * - BABYLON.VertexBuffer.ColorKind
  31326. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31327. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31328. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31329. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31330. */
  31331. Mesh.prototype.getVerticesDataKinds = function () {
  31332. if (!this._geometry) {
  31333. var result = new Array();
  31334. if (this._delayInfo) {
  31335. this._delayInfo.forEach(function (kind, index, array) {
  31336. result.push(kind);
  31337. });
  31338. }
  31339. return result;
  31340. }
  31341. return this._geometry.getVerticesDataKinds();
  31342. };
  31343. /**
  31344. * Returns a positive integer : the total number of indices in this mesh geometry.
  31345. * Returns zero if the mesh has no geometry.
  31346. */
  31347. Mesh.prototype.getTotalIndices = function () {
  31348. if (!this._geometry) {
  31349. return 0;
  31350. }
  31351. return this._geometry.getTotalIndices();
  31352. };
  31353. /**
  31354. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31355. * If the parameter `copyWhenShared` is 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.
  31356. * Returns an empty array if the mesh has no geometry.
  31357. */
  31358. Mesh.prototype.getIndices = function (copyWhenShared) {
  31359. if (!this._geometry) {
  31360. return [];
  31361. }
  31362. return this._geometry.getIndices(copyWhenShared);
  31363. };
  31364. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31365. get: function () {
  31366. return this._masterMesh !== null && this._masterMesh !== undefined;
  31367. },
  31368. enumerable: true,
  31369. configurable: true
  31370. });
  31371. /**
  31372. * Determine if the current mesh is ready to be rendered
  31373. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31374. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31375. * @returns true if all associated assets are ready (material, textures, shaders)
  31376. */
  31377. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31378. if (completeCheck === void 0) { completeCheck = false; }
  31379. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31380. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31381. return false;
  31382. }
  31383. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31384. return false;
  31385. }
  31386. if (!this.subMeshes || this.subMeshes.length === 0) {
  31387. return true;
  31388. }
  31389. if (!completeCheck) {
  31390. return true;
  31391. }
  31392. var engine = this.getEngine();
  31393. var scene = this.getScene();
  31394. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31395. this.computeWorldMatrix();
  31396. var mat = this.material || scene.defaultMaterial;
  31397. if (mat) {
  31398. if (mat.storeEffectOnSubMeshes) {
  31399. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31400. var subMesh = _a[_i];
  31401. var effectiveMaterial = subMesh.getMaterial();
  31402. if (effectiveMaterial) {
  31403. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31404. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31405. return false;
  31406. }
  31407. }
  31408. else {
  31409. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31410. return false;
  31411. }
  31412. }
  31413. }
  31414. }
  31415. }
  31416. else {
  31417. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31418. return false;
  31419. }
  31420. }
  31421. }
  31422. // Shadows
  31423. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31424. var light = _c[_b];
  31425. var generator = light.getShadowGenerator();
  31426. if (generator) {
  31427. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31428. var subMesh = _e[_d];
  31429. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31430. return false;
  31431. }
  31432. }
  31433. }
  31434. }
  31435. // LOD
  31436. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31437. var lod = _g[_f];
  31438. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31439. return false;
  31440. }
  31441. }
  31442. return true;
  31443. };
  31444. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31445. /**
  31446. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31447. * This property is pertinent only for updatable parametric shapes.
  31448. */
  31449. get: function () {
  31450. return this._areNormalsFrozen;
  31451. },
  31452. enumerable: true,
  31453. configurable: true
  31454. });
  31455. /**
  31456. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31457. * It has no effect at all on other shapes.
  31458. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31459. * Returns the Mesh.
  31460. */
  31461. Mesh.prototype.freezeNormals = function () {
  31462. this._areNormalsFrozen = true;
  31463. return this;
  31464. };
  31465. /**
  31466. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31467. * It has no effect at all on other shapes.
  31468. * It reactivates the mesh normals computation if it was previously frozen.
  31469. * Returns the Mesh.
  31470. */
  31471. Mesh.prototype.unfreezeNormals = function () {
  31472. this._areNormalsFrozen = false;
  31473. return this;
  31474. };
  31475. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31476. /**
  31477. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31478. */
  31479. set: function (count) {
  31480. this._overridenInstanceCount = count;
  31481. },
  31482. enumerable: true,
  31483. configurable: true
  31484. });
  31485. // Methods
  31486. Mesh.prototype._preActivate = function () {
  31487. var sceneRenderId = this.getScene().getRenderId();
  31488. if (this._preActivateId === sceneRenderId) {
  31489. return this;
  31490. }
  31491. this._preActivateId = sceneRenderId;
  31492. this._visibleInstances = null;
  31493. return this;
  31494. };
  31495. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31496. if (this._visibleInstances) {
  31497. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31498. }
  31499. return this;
  31500. };
  31501. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31502. if (!this._visibleInstances) {
  31503. this._visibleInstances = {};
  31504. this._visibleInstances.defaultRenderId = renderId;
  31505. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31506. }
  31507. if (!this._visibleInstances[renderId]) {
  31508. this._visibleInstances[renderId] = new Array();
  31509. }
  31510. this._visibleInstances[renderId].push(instance);
  31511. return this;
  31512. };
  31513. /**
  31514. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31515. * This means the mesh underlying bounding box and sphere are recomputed.
  31516. * Returns the Mesh.
  31517. */
  31518. Mesh.prototype.refreshBoundingInfo = function () {
  31519. return this._refreshBoundingInfo(false);
  31520. };
  31521. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31522. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31523. return this;
  31524. }
  31525. var data = this._getPositionData(applySkeleton);
  31526. if (data) {
  31527. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31528. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31529. }
  31530. if (this.subMeshes) {
  31531. for (var index = 0; index < this.subMeshes.length; index++) {
  31532. this.subMeshes[index].refreshBoundingInfo();
  31533. }
  31534. }
  31535. this._updateBoundingInfo();
  31536. return this;
  31537. };
  31538. Mesh.prototype._getPositionData = function (applySkeleton) {
  31539. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31540. if (data && applySkeleton && this.skeleton) {
  31541. data = BABYLON.Tools.Slice(data);
  31542. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31543. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31544. if (matricesWeightsData && matricesIndicesData) {
  31545. var needExtras = this.numBoneInfluencers > 4;
  31546. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31547. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31548. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31549. var tempVector = BABYLON.Tmp.Vector3[0];
  31550. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31551. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31552. var matWeightIdx = 0;
  31553. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31554. finalMatrix.reset();
  31555. var inf;
  31556. var weight;
  31557. for (inf = 0; inf < 4; inf++) {
  31558. weight = matricesWeightsData[matWeightIdx + inf];
  31559. if (weight <= 0)
  31560. break;
  31561. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31562. finalMatrix.addToSelf(tempMatrix);
  31563. }
  31564. if (needExtras) {
  31565. for (inf = 0; inf < 4; inf++) {
  31566. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31567. if (weight <= 0)
  31568. break;
  31569. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31570. finalMatrix.addToSelf(tempMatrix);
  31571. }
  31572. }
  31573. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31574. tempVector.toArray(data, index);
  31575. }
  31576. }
  31577. }
  31578. return data;
  31579. };
  31580. Mesh.prototype._createGlobalSubMesh = function (force) {
  31581. var totalVertices = this.getTotalVertices();
  31582. if (!totalVertices || !this.getIndices()) {
  31583. return null;
  31584. }
  31585. // Check if we need to recreate the submeshes
  31586. if (this.subMeshes && this.subMeshes.length > 0) {
  31587. var ib = this.getIndices();
  31588. if (!ib) {
  31589. return null;
  31590. }
  31591. var totalIndices = ib.length;
  31592. var needToRecreate = false;
  31593. if (force) {
  31594. needToRecreate = true;
  31595. }
  31596. else {
  31597. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31598. var submesh = _a[_i];
  31599. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31600. needToRecreate = true;
  31601. break;
  31602. }
  31603. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31604. needToRecreate = true;
  31605. break;
  31606. }
  31607. }
  31608. }
  31609. if (!needToRecreate) {
  31610. return this.subMeshes[0];
  31611. }
  31612. }
  31613. this.releaseSubMeshes();
  31614. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31615. };
  31616. Mesh.prototype.subdivide = function (count) {
  31617. if (count < 1) {
  31618. return;
  31619. }
  31620. var totalIndices = this.getTotalIndices();
  31621. var subdivisionSize = (totalIndices / count) | 0;
  31622. var offset = 0;
  31623. // Ensure that subdivisionSize is a multiple of 3
  31624. while (subdivisionSize % 3 !== 0) {
  31625. subdivisionSize++;
  31626. }
  31627. this.releaseSubMeshes();
  31628. for (var index = 0; index < count; index++) {
  31629. if (offset >= totalIndices) {
  31630. break;
  31631. }
  31632. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31633. offset += subdivisionSize;
  31634. }
  31635. this.synchronizeInstances();
  31636. };
  31637. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31638. if (updatable === void 0) { updatable = false; }
  31639. if (!this._geometry) {
  31640. var vertexData = new BABYLON.VertexData();
  31641. vertexData.set(data, kind);
  31642. var scene = this.getScene();
  31643. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31644. }
  31645. else {
  31646. this._geometry.setVerticesData(kind, data, updatable, stride);
  31647. }
  31648. return this;
  31649. };
  31650. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31651. if (updatable === void 0) { updatable = true; }
  31652. var vb = this.getVertexBuffer(kind);
  31653. if (!vb || vb.isUpdatable() === updatable) {
  31654. return;
  31655. }
  31656. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31657. };
  31658. /**
  31659. * Sets the mesh VertexBuffer.
  31660. * Returns the Mesh.
  31661. */
  31662. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31663. if (!this._geometry) {
  31664. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31665. }
  31666. this._geometry.setVerticesBuffer(buffer);
  31667. return this;
  31668. };
  31669. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31670. if (!this._geometry) {
  31671. return this;
  31672. }
  31673. if (!makeItUnique) {
  31674. this._geometry.updateVerticesData(kind, data, updateExtends);
  31675. }
  31676. else {
  31677. this.makeGeometryUnique();
  31678. this.updateVerticesData(kind, data, updateExtends, false);
  31679. }
  31680. return this;
  31681. };
  31682. /**
  31683. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31684. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31685. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31686. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31687. * Returns the Mesh.
  31688. */
  31689. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31690. if (computeNormals === void 0) { computeNormals = true; }
  31691. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31692. if (!positions) {
  31693. return this;
  31694. }
  31695. positionFunction(positions);
  31696. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31697. if (computeNormals) {
  31698. var indices = this.getIndices();
  31699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31700. if (!normals) {
  31701. return this;
  31702. }
  31703. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31704. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31705. }
  31706. return this;
  31707. };
  31708. /**
  31709. * Creates a un-shared specific occurence of the geometry for the mesh.
  31710. * Returns the Mesh.
  31711. */
  31712. Mesh.prototype.makeGeometryUnique = function () {
  31713. if (!this._geometry) {
  31714. return this;
  31715. }
  31716. var oldGeometry = this._geometry;
  31717. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31718. oldGeometry.releaseForMesh(this, true);
  31719. geometry.applyToMesh(this);
  31720. return this;
  31721. };
  31722. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31723. if (totalVertices === void 0) { totalVertices = null; }
  31724. if (updatable === void 0) { updatable = false; }
  31725. if (!this._geometry) {
  31726. var vertexData = new BABYLON.VertexData();
  31727. vertexData.indices = indices;
  31728. var scene = this.getScene();
  31729. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31730. }
  31731. else {
  31732. this._geometry.setIndices(indices, totalVertices, updatable);
  31733. }
  31734. return this;
  31735. };
  31736. /**
  31737. * Update the current index buffer
  31738. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31739. * Returns the Mesh.
  31740. */
  31741. Mesh.prototype.updateIndices = function (indices, offset) {
  31742. if (!this._geometry) {
  31743. return this;
  31744. }
  31745. this._geometry.updateIndices(indices, offset);
  31746. return this;
  31747. };
  31748. /**
  31749. * Invert the geometry to move from a right handed system to a left handed one.
  31750. * Returns the Mesh.
  31751. */
  31752. Mesh.prototype.toLeftHanded = function () {
  31753. if (!this._geometry) {
  31754. return this;
  31755. }
  31756. this._geometry.toLeftHanded();
  31757. return this;
  31758. };
  31759. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31760. if (!this._geometry) {
  31761. return this;
  31762. }
  31763. var engine = this.getScene().getEngine();
  31764. // Wireframe
  31765. var indexToBind;
  31766. if (this._unIndexed) {
  31767. indexToBind = null;
  31768. }
  31769. else {
  31770. switch (fillMode) {
  31771. case BABYLON.Material.PointFillMode:
  31772. indexToBind = null;
  31773. break;
  31774. case BABYLON.Material.WireFrameFillMode:
  31775. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31776. break;
  31777. default:
  31778. case BABYLON.Material.TriangleFillMode:
  31779. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31780. break;
  31781. }
  31782. }
  31783. // VBOs
  31784. this._geometry._bind(effect, indexToBind);
  31785. return this;
  31786. };
  31787. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31788. if (alternate === void 0) { alternate = false; }
  31789. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31790. return this;
  31791. }
  31792. this.onBeforeDrawObservable.notifyObservers(this);
  31793. var scene = this.getScene();
  31794. var engine = scene.getEngine();
  31795. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31796. // or triangles as points
  31797. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31798. }
  31799. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31800. // Triangles as wireframe
  31801. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31802. }
  31803. else {
  31804. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31805. }
  31806. if (scene._isAlternateRenderingEnabled && !alternate) {
  31807. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31808. if (!effect || !scene.activeCamera) {
  31809. return this;
  31810. }
  31811. scene._switchToAlternateCameraConfiguration(true);
  31812. this._effectiveMaterial.bindView(effect);
  31813. this._effectiveMaterial.bindViewProjection(effect);
  31814. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31815. this._draw(subMesh, fillMode, instancesCount, true);
  31816. engine.setViewport(scene.activeCamera.viewport);
  31817. scene._switchToAlternateCameraConfiguration(false);
  31818. this._effectiveMaterial.bindView(effect);
  31819. this._effectiveMaterial.bindViewProjection(effect);
  31820. }
  31821. return this;
  31822. };
  31823. /**
  31824. * Registers for this mesh a javascript function called just before the rendering process.
  31825. * This function is passed the current mesh.
  31826. * Return the Mesh.
  31827. */
  31828. Mesh.prototype.registerBeforeRender = function (func) {
  31829. this.onBeforeRenderObservable.add(func);
  31830. return this;
  31831. };
  31832. /**
  31833. * Disposes a previously registered javascript function called before the rendering.
  31834. * This function is passed the current mesh.
  31835. * Returns the Mesh.
  31836. */
  31837. Mesh.prototype.unregisterBeforeRender = function (func) {
  31838. this.onBeforeRenderObservable.removeCallback(func);
  31839. return this;
  31840. };
  31841. /**
  31842. * Registers for this mesh a javascript function called just after the rendering is complete.
  31843. * This function is passed the current mesh.
  31844. * Returns the Mesh.
  31845. */
  31846. Mesh.prototype.registerAfterRender = function (func) {
  31847. this.onAfterRenderObservable.add(func);
  31848. return this;
  31849. };
  31850. /**
  31851. * Disposes a previously registered javascript function called after the rendering.
  31852. * This function is passed the current mesh.
  31853. * Return the Mesh.
  31854. */
  31855. Mesh.prototype.unregisterAfterRender = function (func) {
  31856. this.onAfterRenderObservable.removeCallback(func);
  31857. return this;
  31858. };
  31859. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31860. var scene = this.getScene();
  31861. this._batchCache.mustReturn = false;
  31862. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31863. this._batchCache.visibleInstances[subMeshId] = null;
  31864. if (this._visibleInstances) {
  31865. var currentRenderId = scene.getRenderId();
  31866. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31867. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31868. var selfRenderId = this._renderId;
  31869. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31870. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31871. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31872. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31873. }
  31874. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31875. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31876. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31877. this._batchCache.mustReturn = true;
  31878. return this._batchCache;
  31879. }
  31880. if (currentRenderId !== selfRenderId) {
  31881. this._batchCache.renderSelf[subMeshId] = false;
  31882. }
  31883. }
  31884. this._renderIdForInstances[subMeshId] = currentRenderId;
  31885. }
  31886. return this._batchCache;
  31887. };
  31888. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31889. var visibleInstances = batch.visibleInstances[subMesh._id];
  31890. if (!visibleInstances) {
  31891. return this;
  31892. }
  31893. var matricesCount = visibleInstances.length + 1;
  31894. var bufferSize = matricesCount * 16 * 4;
  31895. var currentInstancesBufferSize = this._instancesBufferSize;
  31896. var instancesBuffer = this._instancesBuffer;
  31897. while (this._instancesBufferSize < bufferSize) {
  31898. this._instancesBufferSize *= 2;
  31899. }
  31900. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31901. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31902. }
  31903. var offset = 0;
  31904. var instancesCount = 0;
  31905. var world = this.getWorldMatrix();
  31906. if (batch.renderSelf[subMesh._id]) {
  31907. world.copyToArray(this._instancesData, offset);
  31908. offset += 16;
  31909. instancesCount++;
  31910. }
  31911. if (visibleInstances) {
  31912. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31913. var instance = visibleInstances[instanceIndex];
  31914. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31915. offset += 16;
  31916. instancesCount++;
  31917. }
  31918. }
  31919. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31920. if (instancesBuffer) {
  31921. instancesBuffer.dispose();
  31922. }
  31923. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31924. this._instancesBuffer = instancesBuffer;
  31925. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31926. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31927. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31928. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31929. }
  31930. else {
  31931. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31932. }
  31933. this._bind(subMesh, effect, fillMode);
  31934. this._draw(subMesh, fillMode, instancesCount);
  31935. engine.unbindInstanceAttributes();
  31936. return this;
  31937. };
  31938. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31939. var scene = this.getScene();
  31940. var engine = scene.getEngine();
  31941. if (hardwareInstancedRendering) {
  31942. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31943. }
  31944. else {
  31945. if (batch.renderSelf[subMesh._id]) {
  31946. // Draw
  31947. if (onBeforeDraw) {
  31948. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31949. }
  31950. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31951. }
  31952. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31953. if (visibleInstancesForSubMesh) {
  31954. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31955. var instance = visibleInstancesForSubMesh[instanceIndex];
  31956. // World
  31957. var world = instance.getWorldMatrix();
  31958. if (onBeforeDraw) {
  31959. onBeforeDraw(true, world, effectiveMaterial);
  31960. }
  31961. // Draw
  31962. this._draw(subMesh, fillMode);
  31963. }
  31964. }
  31965. }
  31966. return this;
  31967. };
  31968. /**
  31969. * Triggers the draw call for the mesh.
  31970. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31971. * Returns the Mesh.
  31972. */
  31973. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31974. this._checkOcclusionQuery();
  31975. if (this._isOccluded) {
  31976. return this;
  31977. }
  31978. var scene = this.getScene();
  31979. // Managing instances
  31980. var batch = this._getInstancesRenderList(subMesh._id);
  31981. if (batch.mustReturn) {
  31982. return this;
  31983. }
  31984. // Checking geometry state
  31985. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31986. return this;
  31987. }
  31988. this.onBeforeRenderObservable.notifyObservers(this);
  31989. var engine = scene.getEngine();
  31990. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31991. // Material
  31992. var material = subMesh.getMaterial();
  31993. if (!material) {
  31994. return this;
  31995. }
  31996. this._effectiveMaterial = material;
  31997. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31998. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31999. return this;
  32000. }
  32001. }
  32002. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32003. return this;
  32004. }
  32005. // Alpha mode
  32006. if (enableAlphaMode) {
  32007. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32008. }
  32009. // Outline - step 1
  32010. var savedDepthWrite = engine.getDepthWrite();
  32011. if (this.renderOutline) {
  32012. engine.setDepthWrite(false);
  32013. scene.getOutlineRenderer().render(subMesh, batch);
  32014. engine.setDepthWrite(savedDepthWrite);
  32015. }
  32016. var effect;
  32017. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32018. effect = subMesh.effect;
  32019. }
  32020. else {
  32021. effect = this._effectiveMaterial.getEffect();
  32022. }
  32023. if (!effect) {
  32024. return this;
  32025. }
  32026. var sideOrientation = this.overrideMaterialSideOrientation;
  32027. if (sideOrientation == null) {
  32028. sideOrientation = this._effectiveMaterial.sideOrientation;
  32029. if (this._getWorldMatrixDeterminant() < 0) {
  32030. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32031. }
  32032. }
  32033. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32034. if (this._effectiveMaterial.forceDepthWrite) {
  32035. engine.setDepthWrite(true);
  32036. }
  32037. // Bind
  32038. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32039. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32040. this._bind(subMesh, effect, fillMode);
  32041. }
  32042. var world = this.getWorldMatrix();
  32043. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32044. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32045. }
  32046. else {
  32047. this._effectiveMaterial.bind(world, this);
  32048. }
  32049. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32050. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32051. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32052. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32053. }
  32054. // Draw
  32055. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32056. // Unbind
  32057. this._effectiveMaterial.unbind();
  32058. // Outline - step 2
  32059. if (this.renderOutline && savedDepthWrite) {
  32060. engine.setDepthWrite(true);
  32061. engine.setColorWrite(false);
  32062. scene.getOutlineRenderer().render(subMesh, batch);
  32063. engine.setColorWrite(true);
  32064. }
  32065. // Overlay
  32066. if (this.renderOverlay) {
  32067. var currentMode = engine.getAlphaMode();
  32068. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32069. scene.getOutlineRenderer().render(subMesh, batch, true);
  32070. engine.setAlphaMode(currentMode);
  32071. }
  32072. this.onAfterRenderObservable.notifyObservers(this);
  32073. return this;
  32074. };
  32075. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32076. if (isInstance && effectiveMaterial) {
  32077. effectiveMaterial.bindOnlyWorldMatrix(world);
  32078. }
  32079. };
  32080. /**
  32081. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32082. */
  32083. Mesh.prototype.getEmittedParticleSystems = function () {
  32084. var results = new Array();
  32085. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32086. var particleSystem = this.getScene().particleSystems[index];
  32087. if (particleSystem.emitter === this) {
  32088. results.push(particleSystem);
  32089. }
  32090. }
  32091. return results;
  32092. };
  32093. /**
  32094. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32095. */
  32096. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32097. var results = new Array();
  32098. var descendants = this.getDescendants();
  32099. descendants.push(this);
  32100. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32101. var particleSystem = this.getScene().particleSystems[index];
  32102. var emitter = particleSystem.emitter;
  32103. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32104. results.push(particleSystem);
  32105. }
  32106. }
  32107. return results;
  32108. };
  32109. Mesh.prototype._checkDelayState = function () {
  32110. var scene = this.getScene();
  32111. if (this._geometry) {
  32112. this._geometry.load(scene);
  32113. }
  32114. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32116. this._queueLoad(scene);
  32117. }
  32118. return this;
  32119. };
  32120. Mesh.prototype._queueLoad = function (scene) {
  32121. var _this = this;
  32122. scene._addPendingData(this);
  32123. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32124. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32125. if (data instanceof ArrayBuffer) {
  32126. _this._delayLoadingFunction(data, _this);
  32127. }
  32128. else {
  32129. _this._delayLoadingFunction(JSON.parse(data), _this);
  32130. }
  32131. _this.instances.forEach(function (instance) {
  32132. instance._syncSubMeshes();
  32133. });
  32134. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32135. scene._removePendingData(_this);
  32136. }, function () { }, scene.database, getBinaryData);
  32137. return this;
  32138. };
  32139. /**
  32140. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32141. */
  32142. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32143. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32144. return false;
  32145. }
  32146. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32147. return false;
  32148. }
  32149. this._checkDelayState();
  32150. return true;
  32151. };
  32152. /**
  32153. * Sets the mesh material by the material or multiMaterial `id` property.
  32154. * The material `id` is a string identifying the material or the multiMaterial.
  32155. * This method returns the Mesh.
  32156. */
  32157. Mesh.prototype.setMaterialByID = function (id) {
  32158. var materials = this.getScene().materials;
  32159. var index;
  32160. for (index = materials.length - 1; index > -1; index--) {
  32161. if (materials[index].id === id) {
  32162. this.material = materials[index];
  32163. return this;
  32164. }
  32165. }
  32166. // Multi
  32167. var multiMaterials = this.getScene().multiMaterials;
  32168. for (index = multiMaterials.length - 1; index > -1; index--) {
  32169. if (multiMaterials[index].id === id) {
  32170. this.material = multiMaterials[index];
  32171. return this;
  32172. }
  32173. }
  32174. return this;
  32175. };
  32176. /**
  32177. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32178. */
  32179. Mesh.prototype.getAnimatables = function () {
  32180. var results = new Array();
  32181. if (this.material) {
  32182. results.push(this.material);
  32183. }
  32184. if (this.skeleton) {
  32185. results.push(this.skeleton);
  32186. }
  32187. return results;
  32188. };
  32189. /**
  32190. * Modifies the mesh geometry according to the passed transformation matrix.
  32191. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32192. * The mesh normals are modified accordingly the same transformation.
  32193. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  32194. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32195. * Returns the Mesh.
  32196. */
  32197. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32198. // Position
  32199. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32200. return this;
  32201. }
  32202. var submeshes = this.subMeshes.splice(0);
  32203. this._resetPointsArrayCache();
  32204. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32205. var temp = new Array();
  32206. var index;
  32207. for (index = 0; index < data.length; index += 3) {
  32208. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32209. }
  32210. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32211. // Normals
  32212. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32213. return this;
  32214. }
  32215. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32216. temp = [];
  32217. for (index = 0; index < data.length; index += 3) {
  32218. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32219. }
  32220. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32221. // flip faces?
  32222. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32223. this.flipFaces();
  32224. }
  32225. // Restore submeshes
  32226. this.releaseSubMeshes();
  32227. this.subMeshes = submeshes;
  32228. return this;
  32229. };
  32230. /**
  32231. * Modifies the mesh geometry according to its own current World Matrix.
  32232. * The mesh World Matrix is then reset.
  32233. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32234. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32235. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32236. * Returns the Mesh.
  32237. */
  32238. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32239. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32240. this.scaling.copyFromFloats(1, 1, 1);
  32241. this.position.copyFromFloats(0, 0, 0);
  32242. this.rotation.copyFromFloats(0, 0, 0);
  32243. //only if quaternion is already set
  32244. if (this.rotationQuaternion) {
  32245. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32246. }
  32247. this._worldMatrix = BABYLON.Matrix.Identity();
  32248. return this;
  32249. };
  32250. Object.defineProperty(Mesh.prototype, "_positions", {
  32251. // Cache
  32252. get: function () {
  32253. if (this._geometry) {
  32254. return this._geometry._positions;
  32255. }
  32256. return null;
  32257. },
  32258. enumerable: true,
  32259. configurable: true
  32260. });
  32261. Mesh.prototype._resetPointsArrayCache = function () {
  32262. if (this._geometry) {
  32263. this._geometry._resetPointsArrayCache();
  32264. }
  32265. return this;
  32266. };
  32267. Mesh.prototype._generatePointsArray = function () {
  32268. if (this._geometry) {
  32269. return this._geometry._generatePointsArray();
  32270. }
  32271. return false;
  32272. };
  32273. /**
  32274. * Returns a new Mesh object generated from the current mesh properties.
  32275. * This method must not get confused with createInstance().
  32276. * The parameter `name` is a string, the name given to the new mesh.
  32277. * The optional parameter `newParent` can be any Node object (default `null`).
  32278. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32279. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32280. */
  32281. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32282. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32283. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32284. };
  32285. /**
  32286. * Releases resources associated with this mesh.
  32287. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32288. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32289. */
  32290. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32291. var _this = this;
  32292. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32293. this.morphTargetManager = null;
  32294. if (this._geometry) {
  32295. this._geometry.releaseForMesh(this, true);
  32296. }
  32297. // Sources
  32298. var meshes = this.getScene().meshes;
  32299. meshes.forEach(function (abstractMesh) {
  32300. var mesh = abstractMesh;
  32301. if (mesh._source && mesh._source === _this) {
  32302. mesh._source = null;
  32303. }
  32304. });
  32305. this._source = null;
  32306. // Instances
  32307. if (this._instancesBuffer) {
  32308. this._instancesBuffer.dispose();
  32309. this._instancesBuffer = null;
  32310. }
  32311. while (this.instances.length) {
  32312. this.instances[0].dispose();
  32313. }
  32314. // Effect layers.
  32315. var effectLayers = this.getScene().effectLayers;
  32316. for (var i = 0; i < effectLayers.length; i++) {
  32317. var effectLayer = effectLayers[i];
  32318. if (effectLayer) {
  32319. effectLayer._disposeMesh(this);
  32320. }
  32321. }
  32322. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32323. };
  32324. /**
  32325. * Modifies the mesh geometry according to a displacement map.
  32326. * 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.
  32327. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32328. * This method returns nothing.
  32329. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32330. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32331. * The parameter `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.
  32332. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32333. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32334. *
  32335. * Returns the Mesh.
  32336. */
  32337. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32338. var _this = this;
  32339. var scene = this.getScene();
  32340. var onload = function (img) {
  32341. // Getting height map data
  32342. var canvas = document.createElement("canvas");
  32343. var context = canvas.getContext("2d");
  32344. var heightMapWidth = img.width;
  32345. var heightMapHeight = img.height;
  32346. canvas.width = heightMapWidth;
  32347. canvas.height = heightMapHeight;
  32348. context.drawImage(img, 0, 0);
  32349. // Create VertexData from map data
  32350. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32351. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32352. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32353. //execute success callback, if set
  32354. if (onSuccess) {
  32355. onSuccess(_this);
  32356. }
  32357. };
  32358. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32359. return this;
  32360. };
  32361. /**
  32362. * Modifies the mesh geometry according to a displacementMap buffer.
  32363. * 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.
  32364. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32365. * This method returns nothing.
  32366. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32367. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32368. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32369. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32370. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32371. *
  32372. * Returns the Mesh.
  32373. */
  32374. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32375. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32376. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32377. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32378. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32379. return this;
  32380. }
  32381. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32382. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32383. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32384. var position = BABYLON.Vector3.Zero();
  32385. var normal = BABYLON.Vector3.Zero();
  32386. var uv = BABYLON.Vector2.Zero();
  32387. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32388. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32389. for (var index = 0; index < positions.length; index += 3) {
  32390. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32391. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32392. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32393. // Compute height
  32394. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32395. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32396. var pos = (u + v * heightMapWidth) * 4;
  32397. var r = buffer[pos] / 255.0;
  32398. var g = buffer[pos + 1] / 255.0;
  32399. var b = buffer[pos + 2] / 255.0;
  32400. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32401. normal.normalize();
  32402. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32403. position = position.add(normal);
  32404. position.toArray(positions, index);
  32405. }
  32406. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32407. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32408. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32409. return this;
  32410. };
  32411. /**
  32412. * Modify the mesh to get a flat shading rendering.
  32413. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32414. * This method returns the Mesh.
  32415. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32416. */
  32417. Mesh.prototype.convertToFlatShadedMesh = function () {
  32418. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32419. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32420. var kinds = this.getVerticesDataKinds();
  32421. var vbs = {};
  32422. var data = {};
  32423. var newdata = {};
  32424. var updatableNormals = false;
  32425. var kindIndex;
  32426. var kind;
  32427. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32428. kind = kinds[kindIndex];
  32429. var vertexBuffer = this.getVertexBuffer(kind);
  32430. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32431. updatableNormals = vertexBuffer.isUpdatable();
  32432. kinds.splice(kindIndex, 1);
  32433. kindIndex--;
  32434. continue;
  32435. }
  32436. vbs[kind] = vertexBuffer;
  32437. data[kind] = vbs[kind].getData();
  32438. newdata[kind] = [];
  32439. }
  32440. // Save previous submeshes
  32441. var previousSubmeshes = this.subMeshes.slice(0);
  32442. var indices = this.getIndices();
  32443. var totalIndices = this.getTotalIndices();
  32444. // Generating unique vertices per face
  32445. var index;
  32446. for (index = 0; index < totalIndices; index++) {
  32447. var vertexIndex = indices[index];
  32448. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32449. kind = kinds[kindIndex];
  32450. var stride = vbs[kind].getStrideSize();
  32451. for (var offset = 0; offset < stride; offset++) {
  32452. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32453. }
  32454. }
  32455. }
  32456. // Updating faces & normal
  32457. var normals = [];
  32458. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32459. for (index = 0; index < totalIndices; index += 3) {
  32460. indices[index] = index;
  32461. indices[index + 1] = index + 1;
  32462. indices[index + 2] = index + 2;
  32463. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32464. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32465. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32466. var p1p2 = p1.subtract(p2);
  32467. var p3p2 = p3.subtract(p2);
  32468. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32469. // Store same normals for every vertex
  32470. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32471. normals.push(normal.x);
  32472. normals.push(normal.y);
  32473. normals.push(normal.z);
  32474. }
  32475. }
  32476. this.setIndices(indices);
  32477. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32478. // Updating vertex buffers
  32479. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32480. kind = kinds[kindIndex];
  32481. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32482. }
  32483. // Updating submeshes
  32484. this.releaseSubMeshes();
  32485. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32486. var previousOne = previousSubmeshes[submeshIndex];
  32487. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32488. }
  32489. this.synchronizeInstances();
  32490. return this;
  32491. };
  32492. /**
  32493. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32494. * In other words, more vertices, no more indices and a single bigger VBO.
  32495. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32496. * Returns the Mesh.
  32497. */
  32498. Mesh.prototype.convertToUnIndexedMesh = function () {
  32499. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32500. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32501. var kinds = this.getVerticesDataKinds();
  32502. var vbs = {};
  32503. var data = {};
  32504. var newdata = {};
  32505. var kindIndex;
  32506. var kind;
  32507. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32508. kind = kinds[kindIndex];
  32509. var vertexBuffer = this.getVertexBuffer(kind);
  32510. vbs[kind] = vertexBuffer;
  32511. data[kind] = vbs[kind].getData();
  32512. newdata[kind] = [];
  32513. }
  32514. // Save previous submeshes
  32515. var previousSubmeshes = this.subMeshes.slice(0);
  32516. var indices = this.getIndices();
  32517. var totalIndices = this.getTotalIndices();
  32518. // Generating unique vertices per face
  32519. var index;
  32520. for (index = 0; index < totalIndices; index++) {
  32521. var vertexIndex = indices[index];
  32522. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32523. kind = kinds[kindIndex];
  32524. var stride = vbs[kind].getStrideSize();
  32525. for (var offset = 0; offset < stride; offset++) {
  32526. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32527. }
  32528. }
  32529. }
  32530. // Updating indices
  32531. for (index = 0; index < totalIndices; index += 3) {
  32532. indices[index] = index;
  32533. indices[index + 1] = index + 1;
  32534. indices[index + 2] = index + 2;
  32535. }
  32536. this.setIndices(indices);
  32537. // Updating vertex buffers
  32538. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32539. kind = kinds[kindIndex];
  32540. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32541. }
  32542. // Updating submeshes
  32543. this.releaseSubMeshes();
  32544. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32545. var previousOne = previousSubmeshes[submeshIndex];
  32546. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32547. }
  32548. this._unIndexed = true;
  32549. this.synchronizeInstances();
  32550. return this;
  32551. };
  32552. /**
  32553. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32554. * This method returns the Mesh.
  32555. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32556. */
  32557. Mesh.prototype.flipFaces = function (flipNormals) {
  32558. if (flipNormals === void 0) { flipNormals = false; }
  32559. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32560. var i;
  32561. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32562. for (i = 0; i < vertex_data.normals.length; i++) {
  32563. vertex_data.normals[i] *= -1;
  32564. }
  32565. }
  32566. if (vertex_data.indices) {
  32567. var temp;
  32568. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32569. // reassign indices
  32570. temp = vertex_data.indices[i + 1];
  32571. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32572. vertex_data.indices[i + 2] = temp;
  32573. }
  32574. }
  32575. vertex_data.applyToMesh(this);
  32576. return this;
  32577. };
  32578. // Instances
  32579. /**
  32580. * Creates a new InstancedMesh object from the mesh model.
  32581. * An instance shares the same properties and the same material than its model.
  32582. * Only these properties of each instance can then be set individually :
  32583. * - position
  32584. * - rotation
  32585. * - rotationQuaternion
  32586. * - setPivotMatrix
  32587. * - scaling
  32588. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32589. * Warning : this method is not supported for Line mesh and LineSystem
  32590. */
  32591. Mesh.prototype.createInstance = function (name) {
  32592. return new BABYLON.InstancedMesh(name, this);
  32593. };
  32594. /**
  32595. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32596. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32597. * This method returns the Mesh.
  32598. */
  32599. Mesh.prototype.synchronizeInstances = function () {
  32600. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32601. var instance = this.instances[instanceIndex];
  32602. instance._syncSubMeshes();
  32603. }
  32604. return this;
  32605. };
  32606. /**
  32607. * Simplify the mesh according to the given array of settings.
  32608. * Function will return immediately and will simplify async. It returns the Mesh.
  32609. * @param settings a collection of simplification settings.
  32610. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32611. * @param type the type of simplification to run.
  32612. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32613. */
  32614. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32615. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32616. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32617. this.getScene().simplificationQueue.addTask({
  32618. settings: settings,
  32619. parallelProcessing: parallelProcessing,
  32620. mesh: this,
  32621. simplificationType: simplificationType,
  32622. successCallback: successCallback
  32623. });
  32624. return this;
  32625. };
  32626. /**
  32627. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32628. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32629. * This should be used together with the simplification to avoid disappearing triangles.
  32630. * Returns the Mesh.
  32631. * @param successCallback an optional success callback to be called after the optimization finished.
  32632. */
  32633. Mesh.prototype.optimizeIndices = function (successCallback) {
  32634. var _this = this;
  32635. var indices = this.getIndices();
  32636. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32637. if (!positions || !indices) {
  32638. return this;
  32639. }
  32640. var vectorPositions = new Array();
  32641. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32642. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32643. }
  32644. var dupes = new Array();
  32645. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32646. var realPos = vectorPositions.length - 1 - iteration;
  32647. var testedPosition = vectorPositions[realPos];
  32648. for (var j = 0; j < realPos; ++j) {
  32649. var againstPosition = vectorPositions[j];
  32650. if (testedPosition.equals(againstPosition)) {
  32651. dupes[realPos] = j;
  32652. break;
  32653. }
  32654. }
  32655. }, function () {
  32656. for (var i = 0; i < indices.length; ++i) {
  32657. indices[i] = dupes[indices[i]] || indices[i];
  32658. }
  32659. //indices are now reordered
  32660. var originalSubMeshes = _this.subMeshes.slice(0);
  32661. _this.setIndices(indices);
  32662. _this.subMeshes = originalSubMeshes;
  32663. if (successCallback) {
  32664. successCallback(_this);
  32665. }
  32666. });
  32667. return this;
  32668. };
  32669. Mesh.prototype.serialize = function (serializationObject) {
  32670. serializationObject.name = this.name;
  32671. serializationObject.id = this.id;
  32672. serializationObject.type = this.getClassName();
  32673. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32674. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32675. }
  32676. serializationObject.position = this.position.asArray();
  32677. if (this.rotationQuaternion) {
  32678. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32679. }
  32680. else if (this.rotation) {
  32681. serializationObject.rotation = this.rotation.asArray();
  32682. }
  32683. serializationObject.scaling = this.scaling.asArray();
  32684. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32685. serializationObject.isEnabled = this.isEnabled(false);
  32686. serializationObject.isVisible = this.isVisible;
  32687. serializationObject.infiniteDistance = this.infiniteDistance;
  32688. serializationObject.pickable = this.isPickable;
  32689. serializationObject.receiveShadows = this.receiveShadows;
  32690. serializationObject.billboardMode = this.billboardMode;
  32691. serializationObject.visibility = this.visibility;
  32692. serializationObject.checkCollisions = this.checkCollisions;
  32693. serializationObject.isBlocker = this.isBlocker;
  32694. // Parent
  32695. if (this.parent) {
  32696. serializationObject.parentId = this.parent.id;
  32697. }
  32698. // Geometry
  32699. serializationObject.isUnIndexed = this.isUnIndexed;
  32700. var geometry = this._geometry;
  32701. if (geometry) {
  32702. var geometryId = geometry.id;
  32703. serializationObject.geometryId = geometryId;
  32704. // SubMeshes
  32705. serializationObject.subMeshes = [];
  32706. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32707. var subMesh = this.subMeshes[subIndex];
  32708. serializationObject.subMeshes.push({
  32709. materialIndex: subMesh.materialIndex,
  32710. verticesStart: subMesh.verticesStart,
  32711. verticesCount: subMesh.verticesCount,
  32712. indexStart: subMesh.indexStart,
  32713. indexCount: subMesh.indexCount
  32714. });
  32715. }
  32716. }
  32717. // Material
  32718. if (this.material) {
  32719. serializationObject.materialId = this.material.id;
  32720. }
  32721. else {
  32722. this.material = null;
  32723. }
  32724. // Morph targets
  32725. if (this.morphTargetManager) {
  32726. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32727. }
  32728. // Skeleton
  32729. if (this.skeleton) {
  32730. serializationObject.skeletonId = this.skeleton.id;
  32731. }
  32732. // Physics
  32733. //TODO implement correct serialization for physics impostors.
  32734. var impostor = this.getPhysicsImpostor();
  32735. if (impostor) {
  32736. serializationObject.physicsMass = impostor.getParam("mass");
  32737. serializationObject.physicsFriction = impostor.getParam("friction");
  32738. serializationObject.physicsRestitution = impostor.getParam("mass");
  32739. serializationObject.physicsImpostor = impostor.type;
  32740. }
  32741. // Metadata
  32742. if (this.metadata) {
  32743. serializationObject.metadata = this.metadata;
  32744. }
  32745. // Instances
  32746. serializationObject.instances = [];
  32747. for (var index = 0; index < this.instances.length; index++) {
  32748. var instance = this.instances[index];
  32749. var serializationInstance = {
  32750. name: instance.name,
  32751. id: instance.id,
  32752. position: instance.position.asArray(),
  32753. scaling: instance.scaling.asArray()
  32754. };
  32755. if (instance.rotationQuaternion) {
  32756. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32757. }
  32758. else if (instance.rotation) {
  32759. serializationInstance.rotation = instance.rotation.asArray();
  32760. }
  32761. serializationObject.instances.push(serializationInstance);
  32762. // Animations
  32763. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32764. serializationInstance.ranges = instance.serializeAnimationRanges();
  32765. }
  32766. //
  32767. // Animations
  32768. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32769. serializationObject.ranges = this.serializeAnimationRanges();
  32770. // Layer mask
  32771. serializationObject.layerMask = this.layerMask;
  32772. // Alpha
  32773. serializationObject.alphaIndex = this.alphaIndex;
  32774. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32775. // Overlay
  32776. serializationObject.overlayAlpha = this.overlayAlpha;
  32777. serializationObject.overlayColor = this.overlayColor.asArray();
  32778. serializationObject.renderOverlay = this.renderOverlay;
  32779. // Fog
  32780. serializationObject.applyFog = this.applyFog;
  32781. // Action Manager
  32782. if (this.actionManager) {
  32783. serializationObject.actions = this.actionManager.serialize(this.name);
  32784. }
  32785. };
  32786. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32787. if (!this.geometry) {
  32788. return;
  32789. }
  32790. this._markSubMeshesAsAttributesDirty();
  32791. var morphTargetManager = this._morphTargetManager;
  32792. if (morphTargetManager && morphTargetManager.vertexCount) {
  32793. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32794. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32795. this.morphTargetManager = null;
  32796. return;
  32797. }
  32798. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32799. var morphTarget = morphTargetManager.getActiveTarget(index);
  32800. var positions = morphTarget.getPositions();
  32801. if (!positions) {
  32802. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32803. return;
  32804. }
  32805. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32806. var normals = morphTarget.getNormals();
  32807. if (normals) {
  32808. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32809. }
  32810. var tangents = morphTarget.getTangents();
  32811. if (tangents) {
  32812. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32813. }
  32814. }
  32815. }
  32816. else {
  32817. var index = 0;
  32818. // Positions
  32819. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32820. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32821. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32822. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32823. }
  32824. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32825. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32826. }
  32827. index++;
  32828. }
  32829. }
  32830. };
  32831. // Statics
  32832. /**
  32833. * Returns a new Mesh object parsed from the source provided.
  32834. * The parameter `parsedMesh` is the source.
  32835. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32836. */
  32837. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32838. var mesh;
  32839. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32840. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32841. }
  32842. else {
  32843. mesh = new Mesh(parsedMesh.name, scene);
  32844. }
  32845. mesh.id = parsedMesh.id;
  32846. if (BABYLON.Tags) {
  32847. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32848. }
  32849. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32850. if (parsedMesh.metadata !== undefined) {
  32851. mesh.metadata = parsedMesh.metadata;
  32852. }
  32853. if (parsedMesh.rotationQuaternion) {
  32854. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32855. }
  32856. else if (parsedMesh.rotation) {
  32857. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32858. }
  32859. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32860. if (parsedMesh.localMatrix) {
  32861. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32862. }
  32863. else if (parsedMesh.pivotMatrix) {
  32864. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32865. }
  32866. mesh.setEnabled(parsedMesh.isEnabled);
  32867. mesh.isVisible = parsedMesh.isVisible;
  32868. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32869. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32870. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32871. if (parsedMesh.applyFog !== undefined) {
  32872. mesh.applyFog = parsedMesh.applyFog;
  32873. }
  32874. if (parsedMesh.pickable !== undefined) {
  32875. mesh.isPickable = parsedMesh.pickable;
  32876. }
  32877. if (parsedMesh.alphaIndex !== undefined) {
  32878. mesh.alphaIndex = parsedMesh.alphaIndex;
  32879. }
  32880. mesh.receiveShadows = parsedMesh.receiveShadows;
  32881. mesh.billboardMode = parsedMesh.billboardMode;
  32882. if (parsedMesh.visibility !== undefined) {
  32883. mesh.visibility = parsedMesh.visibility;
  32884. }
  32885. mesh.checkCollisions = parsedMesh.checkCollisions;
  32886. if (parsedMesh.isBlocker !== undefined) {
  32887. mesh.isBlocker = parsedMesh.isBlocker;
  32888. }
  32889. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32890. // freezeWorldMatrix
  32891. if (parsedMesh.freezeWorldMatrix) {
  32892. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32893. }
  32894. // Parent
  32895. if (parsedMesh.parentId) {
  32896. mesh._waitingParentId = parsedMesh.parentId;
  32897. }
  32898. // Actions
  32899. if (parsedMesh.actions !== undefined) {
  32900. mesh._waitingActions = parsedMesh.actions;
  32901. }
  32902. // Overlay
  32903. if (parsedMesh.overlayAlpha !== undefined) {
  32904. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32905. }
  32906. if (parsedMesh.overlayColor !== undefined) {
  32907. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32908. }
  32909. if (parsedMesh.renderOverlay !== undefined) {
  32910. mesh.renderOverlay = parsedMesh.renderOverlay;
  32911. }
  32912. // Geometry
  32913. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32914. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32915. if (parsedMesh.delayLoadingFile) {
  32916. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32917. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32918. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32919. if (parsedMesh._binaryInfo) {
  32920. mesh._binaryInfo = parsedMesh._binaryInfo;
  32921. }
  32922. mesh._delayInfo = [];
  32923. if (parsedMesh.hasUVs) {
  32924. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32925. }
  32926. if (parsedMesh.hasUVs2) {
  32927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32928. }
  32929. if (parsedMesh.hasUVs3) {
  32930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32931. }
  32932. if (parsedMesh.hasUVs4) {
  32933. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32934. }
  32935. if (parsedMesh.hasUVs5) {
  32936. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32937. }
  32938. if (parsedMesh.hasUVs6) {
  32939. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32940. }
  32941. if (parsedMesh.hasColors) {
  32942. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32943. }
  32944. if (parsedMesh.hasMatricesIndices) {
  32945. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32946. }
  32947. if (parsedMesh.hasMatricesWeights) {
  32948. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32949. }
  32950. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32951. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32952. mesh._checkDelayState();
  32953. }
  32954. }
  32955. else {
  32956. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32957. }
  32958. // Material
  32959. if (parsedMesh.materialId) {
  32960. mesh.setMaterialByID(parsedMesh.materialId);
  32961. }
  32962. else {
  32963. mesh.material = null;
  32964. }
  32965. // Morph targets
  32966. if (parsedMesh.morphTargetManagerId > -1) {
  32967. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32968. }
  32969. // Skeleton
  32970. if (parsedMesh.skeletonId > -1) {
  32971. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32972. if (parsedMesh.numBoneInfluencers) {
  32973. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32974. }
  32975. }
  32976. // Animations
  32977. if (parsedMesh.animations) {
  32978. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32979. var parsedAnimation = parsedMesh.animations[animationIndex];
  32980. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32981. }
  32982. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32983. }
  32984. if (parsedMesh.autoAnimate) {
  32985. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32986. }
  32987. // Layer Mask
  32988. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32989. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32990. }
  32991. else {
  32992. mesh.layerMask = 0x0FFFFFFF;
  32993. }
  32994. // Physics
  32995. if (parsedMesh.physicsImpostor) {
  32996. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32997. mass: parsedMesh.physicsMass,
  32998. friction: parsedMesh.physicsFriction,
  32999. restitution: parsedMesh.physicsRestitution
  33000. }, scene);
  33001. }
  33002. // Instances
  33003. if (parsedMesh.instances) {
  33004. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33005. var parsedInstance = parsedMesh.instances[index];
  33006. var instance = mesh.createInstance(parsedInstance.name);
  33007. if (parsedInstance.id) {
  33008. instance.id = parsedInstance.id;
  33009. }
  33010. if (BABYLON.Tags) {
  33011. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33012. }
  33013. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33014. if (parsedInstance.parentId) {
  33015. instance._waitingParentId = parsedInstance.parentId;
  33016. }
  33017. if (parsedInstance.rotationQuaternion) {
  33018. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33019. }
  33020. else if (parsedInstance.rotation) {
  33021. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33022. }
  33023. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33024. instance.checkCollisions = mesh.checkCollisions;
  33025. if (parsedMesh.animations) {
  33026. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33027. parsedAnimation = parsedMesh.animations[animationIndex];
  33028. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33029. }
  33030. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33031. }
  33032. }
  33033. }
  33034. return mesh;
  33035. };
  33036. /**
  33037. * Creates a ribbon mesh.
  33038. * Please consider using the same method from the MeshBuilder class instead.
  33039. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33040. *
  33041. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33042. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33043. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33044. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33045. * 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.
  33046. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33047. * 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
  33048. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33051. */
  33052. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33053. if (closeArray === void 0) { closeArray = false; }
  33054. if (updatable === void 0) { updatable = false; }
  33055. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33056. pathArray: pathArray,
  33057. closeArray: closeArray,
  33058. closePath: closePath,
  33059. offset: offset,
  33060. updatable: updatable,
  33061. sideOrientation: sideOrientation,
  33062. instance: instance
  33063. }, scene);
  33064. };
  33065. /**
  33066. * Creates a plane polygonal mesh. By default, this is a disc.
  33067. * Please consider using the same method from the MeshBuilder class instead.
  33068. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33069. * 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.
  33070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33073. */
  33074. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33075. if (scene === void 0) { scene = null; }
  33076. var options = {
  33077. radius: radius,
  33078. tessellation: tessellation,
  33079. sideOrientation: sideOrientation,
  33080. updatable: updatable
  33081. };
  33082. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33083. };
  33084. /**
  33085. * Creates a box mesh.
  33086. * Please consider using the same method from the MeshBuilder class instead.
  33087. * The parameter `size` sets the size (float) of each box side (default 1).
  33088. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33091. */
  33092. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33093. if (scene === void 0) { scene = null; }
  33094. var options = {
  33095. size: size,
  33096. sideOrientation: sideOrientation,
  33097. updatable: updatable
  33098. };
  33099. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33100. };
  33101. /**
  33102. * Creates a sphere mesh.
  33103. * Please consider using the same method from the MeshBuilder class instead.
  33104. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33105. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33109. */
  33110. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33111. var options = {
  33112. segments: segments,
  33113. diameterX: diameter,
  33114. diameterY: diameter,
  33115. diameterZ: diameter,
  33116. sideOrientation: sideOrientation,
  33117. updatable: updatable
  33118. };
  33119. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33120. };
  33121. /**
  33122. * Creates a cylinder or a cone mesh.
  33123. * Please consider using the same method from the MeshBuilder class instead.
  33124. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33125. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33126. * 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.
  33127. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33128. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33129. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33132. */
  33133. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33134. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33135. if (scene !== undefined) {
  33136. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33137. updatable = scene;
  33138. }
  33139. scene = subdivisions;
  33140. subdivisions = 1;
  33141. }
  33142. var options = {
  33143. height: height,
  33144. diameterTop: diameterTop,
  33145. diameterBottom: diameterBottom,
  33146. tessellation: tessellation,
  33147. subdivisions: subdivisions,
  33148. sideOrientation: sideOrientation,
  33149. updatable: updatable
  33150. };
  33151. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33152. };
  33153. // Torus (Code from SharpDX.org)
  33154. /**
  33155. * Creates a torus mesh.
  33156. * Please consider using the same method from the MeshBuilder class instead.
  33157. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33158. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33159. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33161. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33163. */
  33164. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33165. var options = {
  33166. diameter: diameter,
  33167. thickness: thickness,
  33168. tessellation: tessellation,
  33169. sideOrientation: sideOrientation,
  33170. updatable: updatable
  33171. };
  33172. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33173. };
  33174. /**
  33175. * Creates a torus knot mesh.
  33176. * Please consider using the same method from the MeshBuilder class instead.
  33177. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33178. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33179. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33180. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33182. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33184. */
  33185. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33186. var options = {
  33187. radius: radius,
  33188. tube: tube,
  33189. radialSegments: radialSegments,
  33190. tubularSegments: tubularSegments,
  33191. p: p,
  33192. q: q,
  33193. sideOrientation: sideOrientation,
  33194. updatable: updatable
  33195. };
  33196. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33197. };
  33198. /**
  33199. * Creates a line mesh.
  33200. * Please consider using the same method from the MeshBuilder class instead.
  33201. * 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.
  33202. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33203. * The parameter `points` is an array successive Vector3.
  33204. * 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
  33205. * When updating an instance, remember that only point positions can change, not the number of points.
  33206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33207. */
  33208. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33209. if (scene === void 0) { scene = null; }
  33210. if (updatable === void 0) { updatable = false; }
  33211. if (instance === void 0) { instance = null; }
  33212. var options = {
  33213. points: points,
  33214. updatable: updatable,
  33215. instance: instance
  33216. };
  33217. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33218. };
  33219. /**
  33220. * Creates a dashed line mesh.
  33221. * Please consider using the same method from the MeshBuilder class instead.
  33222. * 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.
  33223. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33224. * The parameter `points` is an array successive Vector3.
  33225. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33226. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33227. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33228. * 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
  33229. * When updating an instance, remember that only point positions can change, not the number of points.
  33230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33231. */
  33232. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33233. if (scene === void 0) { scene = null; }
  33234. var options = {
  33235. points: points,
  33236. dashSize: dashSize,
  33237. gapSize: gapSize,
  33238. dashNb: dashNb,
  33239. updatable: updatable,
  33240. instance: instance
  33241. };
  33242. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33243. };
  33244. /**
  33245. * Creates a polygon mesh.
  33246. * Please consider using the same method from the MeshBuilder class instead.
  33247. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33248. * 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.
  33249. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33251. * Remember you can only change the shape positions, not their number when updating a polygon.
  33252. */
  33253. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33254. var options = {
  33255. shape: shape,
  33256. holes: holes,
  33257. updatable: updatable,
  33258. sideOrientation: sideOrientation
  33259. };
  33260. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33261. };
  33262. /**
  33263. * Creates an extruded polygon mesh, with depth in the Y direction.
  33264. * Please consider using the same method from the MeshBuilder class instead.
  33265. */
  33266. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33267. var options = {
  33268. shape: shape,
  33269. holes: holes,
  33270. depth: depth,
  33271. updatable: updatable,
  33272. sideOrientation: sideOrientation
  33273. };
  33274. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33275. };
  33276. /**
  33277. * Creates an extruded shape mesh.
  33278. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33279. * Please consider using the same method from the MeshBuilder class instead.
  33280. *
  33281. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33282. * 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
  33283. * extruded along the Z axis.
  33284. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33285. * 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.
  33286. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33287. * 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
  33288. * 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
  33289. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33291. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33293. */
  33294. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33295. if (scene === void 0) { scene = null; }
  33296. var options = {
  33297. shape: shape,
  33298. path: path,
  33299. scale: scale,
  33300. rotation: rotation,
  33301. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33302. sideOrientation: sideOrientation,
  33303. instance: instance,
  33304. updatable: updatable
  33305. };
  33306. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33307. };
  33308. /**
  33309. * Creates an custom extruded shape mesh.
  33310. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33311. * Please consider using the same method from the MeshBuilder class instead.
  33312. *
  33313. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33314. * 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
  33315. * extruded along the Z axis.
  33316. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33317. * 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
  33318. * and the distance of this point from the begining of the path :
  33319. * ```javascript
  33320. * var rotationFunction = function(i, distance) {
  33321. * // do things
  33322. * return rotationValue; }
  33323. * ```
  33324. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33325. * 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
  33326. * and the distance of this point from the begining of the path :
  33327. * ```javascript
  33328. * var scaleFunction = function(i, distance) {
  33329. * // do things
  33330. * return scaleValue;}
  33331. * ```
  33332. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33333. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33334. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33335. * 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
  33336. * 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
  33337. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33341. */
  33342. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33343. var options = {
  33344. shape: shape,
  33345. path: path,
  33346. scaleFunction: scaleFunction,
  33347. rotationFunction: rotationFunction,
  33348. ribbonCloseArray: ribbonCloseArray,
  33349. ribbonClosePath: ribbonClosePath,
  33350. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33351. sideOrientation: sideOrientation,
  33352. instance: instance,
  33353. updatable: updatable
  33354. };
  33355. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33356. };
  33357. /**
  33358. * Creates lathe mesh.
  33359. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33360. * Please consider using the same method from the MeshBuilder class instead.
  33361. * 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
  33362. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33363. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33364. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33368. */
  33369. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33370. var options = {
  33371. shape: shape,
  33372. radius: radius,
  33373. tessellation: tessellation,
  33374. sideOrientation: sideOrientation,
  33375. updatable: updatable
  33376. };
  33377. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33378. };
  33379. /**
  33380. * Creates a plane mesh.
  33381. * Please consider using the same method from the MeshBuilder class instead.
  33382. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33383. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33384. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33386. */
  33387. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33388. var options = {
  33389. size: size,
  33390. width: size,
  33391. height: size,
  33392. sideOrientation: sideOrientation,
  33393. updatable: updatable
  33394. };
  33395. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33396. };
  33397. /**
  33398. * Creates a ground mesh.
  33399. * Please consider using the same method from the MeshBuilder class instead.
  33400. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33401. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33403. */
  33404. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33405. var options = {
  33406. width: width,
  33407. height: height,
  33408. subdivisions: subdivisions,
  33409. updatable: updatable
  33410. };
  33411. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33412. };
  33413. /**
  33414. * Creates a tiled ground mesh.
  33415. * Please consider using the same method from the MeshBuilder class instead.
  33416. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33417. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33418. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33419. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33420. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33421. * numbers of subdivisions on the ground width and height of each tile.
  33422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33423. */
  33424. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33425. var options = {
  33426. xmin: xmin,
  33427. zmin: zmin,
  33428. xmax: xmax,
  33429. zmax: zmax,
  33430. subdivisions: subdivisions,
  33431. precision: precision,
  33432. updatable: updatable
  33433. };
  33434. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33435. };
  33436. /**
  33437. * Creates a ground mesh from a height map.
  33438. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33439. * Please consider using the same method from the MeshBuilder class instead.
  33440. * The parameter `url` sets the URL of the height map image resource.
  33441. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33442. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33443. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33444. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33445. * 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).
  33446. * This function is passed the newly built mesh :
  33447. * ```javascript
  33448. * function(mesh) { // do things
  33449. * return; }
  33450. * ```
  33451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33452. */
  33453. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33454. var options = {
  33455. width: width,
  33456. height: height,
  33457. subdivisions: subdivisions,
  33458. minHeight: minHeight,
  33459. maxHeight: maxHeight,
  33460. updatable: updatable,
  33461. onReady: onReady
  33462. };
  33463. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33464. };
  33465. /**
  33466. * Creates a tube mesh.
  33467. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33468. * Please consider using the same method from the MeshBuilder class instead.
  33469. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33470. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33471. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33472. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33473. * 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.
  33474. * It must return a radius value (positive float) :
  33475. * ```javascript
  33476. * var radiusFunction = function(i, distance) {
  33477. * // do things
  33478. * return radius; }
  33479. * ```
  33480. * 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
  33481. * 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
  33482. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33484. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33485. */
  33486. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33487. var options = {
  33488. path: path,
  33489. radius: radius,
  33490. tessellation: tessellation,
  33491. radiusFunction: radiusFunction,
  33492. arc: 1,
  33493. cap: cap,
  33494. updatable: updatable,
  33495. sideOrientation: sideOrientation,
  33496. instance: instance
  33497. };
  33498. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33499. };
  33500. /**
  33501. * Creates a polyhedron mesh.
  33502. * Please consider using the same method from the MeshBuilder class instead.
  33503. * 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
  33504. * to choose the wanted type.
  33505. * The parameter `size` (positive float, default 1) sets the polygon size.
  33506. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33507. * 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`.
  33508. * 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
  33509. * 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)`).
  33510. * 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
  33511. * 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.
  33512. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33513. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33515. */
  33516. Mesh.CreatePolyhedron = function (name, options, scene) {
  33517. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33518. };
  33519. /**
  33520. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33521. * Please consider using the same method from the MeshBuilder class instead.
  33522. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33523. * 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`).
  33524. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33525. * 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.
  33526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33527. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33529. */
  33530. Mesh.CreateIcoSphere = function (name, options, scene) {
  33531. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33532. };
  33533. /**
  33534. * Creates a decal mesh.
  33535. * Please consider using the same method from the MeshBuilder class instead.
  33536. * 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.
  33537. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33538. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33539. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33540. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33541. */
  33542. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33543. var options = {
  33544. position: position,
  33545. normal: normal,
  33546. size: size,
  33547. angle: angle
  33548. };
  33549. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33550. };
  33551. // Skeletons
  33552. /**
  33553. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33554. */
  33555. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33556. if (!this._sourcePositions) {
  33557. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33558. if (!source) {
  33559. return this._sourcePositions;
  33560. }
  33561. this._sourcePositions = new Float32Array(source);
  33562. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33563. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33564. }
  33565. }
  33566. return this._sourcePositions;
  33567. };
  33568. /**
  33569. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33570. */
  33571. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33572. if (!this._sourceNormals) {
  33573. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33574. if (!source) {
  33575. return this._sourceNormals;
  33576. }
  33577. this._sourceNormals = new Float32Array(source);
  33578. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33579. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33580. }
  33581. }
  33582. return this._sourceNormals;
  33583. };
  33584. /**
  33585. * Updates the vertex buffer by applying transformation from the bones.
  33586. * Returns the Mesh.
  33587. *
  33588. * @param {skeleton} skeleton to apply
  33589. */
  33590. Mesh.prototype.applySkeleton = function (skeleton) {
  33591. if (!this.geometry) {
  33592. return this;
  33593. }
  33594. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33595. return this;
  33596. }
  33597. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33598. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33599. return this;
  33600. }
  33601. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33602. return this;
  33603. }
  33604. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33605. return this;
  33606. }
  33607. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33608. return this;
  33609. }
  33610. if (!this._sourcePositions) {
  33611. var submeshes = this.subMeshes.slice();
  33612. this.setPositionsForCPUSkinning();
  33613. this.subMeshes = submeshes;
  33614. }
  33615. if (!this._sourceNormals) {
  33616. this.setNormalsForCPUSkinning();
  33617. }
  33618. // positionsData checks for not being Float32Array will only pass at most once
  33619. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33620. if (!positionsData) {
  33621. return this;
  33622. }
  33623. if (!(positionsData instanceof Float32Array)) {
  33624. positionsData = new Float32Array(positionsData);
  33625. }
  33626. // normalsData checks for not being Float32Array will only pass at most once
  33627. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33628. if (!normalsData) {
  33629. return this;
  33630. }
  33631. if (!(normalsData instanceof Float32Array)) {
  33632. normalsData = new Float32Array(normalsData);
  33633. }
  33634. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33635. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33636. if (!matricesWeightsData || !matricesIndicesData) {
  33637. return this;
  33638. }
  33639. var needExtras = this.numBoneInfluencers > 4;
  33640. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33641. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33642. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33643. var tempVector3 = BABYLON.Vector3.Zero();
  33644. var finalMatrix = new BABYLON.Matrix();
  33645. var tempMatrix = new BABYLON.Matrix();
  33646. var matWeightIdx = 0;
  33647. var inf;
  33648. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33649. var weight;
  33650. for (inf = 0; inf < 4; inf++) {
  33651. weight = matricesWeightsData[matWeightIdx + inf];
  33652. if (weight > 0) {
  33653. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33654. finalMatrix.addToSelf(tempMatrix);
  33655. }
  33656. else
  33657. break;
  33658. }
  33659. if (needExtras) {
  33660. for (inf = 0; inf < 4; inf++) {
  33661. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33662. if (weight > 0) {
  33663. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33664. finalMatrix.addToSelf(tempMatrix);
  33665. }
  33666. else
  33667. break;
  33668. }
  33669. }
  33670. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33671. tempVector3.toArray(positionsData, index);
  33672. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33673. tempVector3.toArray(normalsData, index);
  33674. finalMatrix.reset();
  33675. }
  33676. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33677. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33678. return this;
  33679. };
  33680. // Tools
  33681. /**
  33682. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33683. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33684. */
  33685. Mesh.MinMax = function (meshes) {
  33686. var minVector = null;
  33687. var maxVector = null;
  33688. meshes.forEach(function (mesh, index, array) {
  33689. var boundingInfo = mesh.getBoundingInfo();
  33690. var boundingBox = boundingInfo.boundingBox;
  33691. if (!minVector || !maxVector) {
  33692. minVector = boundingBox.minimumWorld;
  33693. maxVector = boundingBox.maximumWorld;
  33694. }
  33695. else {
  33696. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33697. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33698. }
  33699. });
  33700. if (!minVector || !maxVector) {
  33701. return {
  33702. min: BABYLON.Vector3.Zero(),
  33703. max: BABYLON.Vector3.Zero()
  33704. };
  33705. }
  33706. return {
  33707. min: minVector,
  33708. max: maxVector
  33709. };
  33710. };
  33711. /**
  33712. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33713. */
  33714. Mesh.Center = function (meshesOrMinMaxVector) {
  33715. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33716. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33717. };
  33718. /**
  33719. * Merge the array of meshes into a single mesh for performance reasons.
  33720. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33721. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33722. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33723. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33724. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33725. */
  33726. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33727. if (disposeSource === void 0) { disposeSource = true; }
  33728. var index;
  33729. if (!allow32BitsIndices) {
  33730. var totalVertices = 0;
  33731. // Counting vertices
  33732. for (index = 0; index < meshes.length; index++) {
  33733. if (meshes[index]) {
  33734. totalVertices += meshes[index].getTotalVertices();
  33735. if (totalVertices > 65536) {
  33736. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33737. return null;
  33738. }
  33739. }
  33740. }
  33741. }
  33742. // Merge
  33743. var vertexData = null;
  33744. var otherVertexData;
  33745. var indiceArray = new Array();
  33746. var source = null;
  33747. for (index = 0; index < meshes.length; index++) {
  33748. if (meshes[index]) {
  33749. meshes[index].computeWorldMatrix(true);
  33750. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33751. otherVertexData.transform(meshes[index].getWorldMatrix());
  33752. if (vertexData) {
  33753. vertexData.merge(otherVertexData);
  33754. }
  33755. else {
  33756. vertexData = otherVertexData;
  33757. source = meshes[index];
  33758. }
  33759. if (subdivideWithSubMeshes) {
  33760. indiceArray.push(meshes[index].getTotalIndices());
  33761. }
  33762. }
  33763. }
  33764. source = source;
  33765. if (!meshSubclass) {
  33766. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33767. }
  33768. vertexData.applyToMesh(meshSubclass);
  33769. // Setting properties
  33770. meshSubclass.material = source.material;
  33771. meshSubclass.checkCollisions = source.checkCollisions;
  33772. // Cleaning
  33773. if (disposeSource) {
  33774. for (index = 0; index < meshes.length; index++) {
  33775. if (meshes[index]) {
  33776. meshes[index].dispose();
  33777. }
  33778. }
  33779. }
  33780. // Subdivide
  33781. if (subdivideWithSubMeshes) {
  33782. //-- Suppresions du submesh global
  33783. meshSubclass.releaseSubMeshes();
  33784. index = 0;
  33785. var offset = 0;
  33786. //-- aplique la subdivision en fonction du tableau d'indices
  33787. while (index < indiceArray.length) {
  33788. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33789. offset += indiceArray[index];
  33790. index++;
  33791. }
  33792. }
  33793. return meshSubclass;
  33794. };
  33795. // Consts
  33796. Mesh._FRONTSIDE = 0;
  33797. Mesh._BACKSIDE = 1;
  33798. Mesh._DOUBLESIDE = 2;
  33799. Mesh._DEFAULTSIDE = 0;
  33800. Mesh._NO_CAP = 0;
  33801. Mesh._CAP_START = 1;
  33802. Mesh._CAP_END = 2;
  33803. Mesh._CAP_ALL = 3;
  33804. return Mesh;
  33805. }(BABYLON.AbstractMesh));
  33806. BABYLON.Mesh = Mesh;
  33807. })(BABYLON || (BABYLON = {}));
  33808. //# sourceMappingURL=babylon.mesh.js.map
  33809. var BABYLON;
  33810. (function (BABYLON) {
  33811. var BaseSubMesh = /** @class */ (function () {
  33812. function BaseSubMesh() {
  33813. }
  33814. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33815. get: function () {
  33816. return this._materialEffect;
  33817. },
  33818. enumerable: true,
  33819. configurable: true
  33820. });
  33821. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33822. if (defines === void 0) { defines = null; }
  33823. if (this._materialEffect === effect) {
  33824. if (!effect) {
  33825. this._materialDefines = null;
  33826. }
  33827. return;
  33828. }
  33829. this._materialDefines = defines;
  33830. this._materialEffect = effect;
  33831. };
  33832. return BaseSubMesh;
  33833. }());
  33834. BABYLON.BaseSubMesh = BaseSubMesh;
  33835. var SubMesh = /** @class */ (function (_super) {
  33836. __extends(SubMesh, _super);
  33837. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33838. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33839. var _this = _super.call(this) || this;
  33840. _this.materialIndex = materialIndex;
  33841. _this.verticesStart = verticesStart;
  33842. _this.verticesCount = verticesCount;
  33843. _this.indexStart = indexStart;
  33844. _this.indexCount = indexCount;
  33845. _this._renderId = 0;
  33846. _this._mesh = mesh;
  33847. _this._renderingMesh = renderingMesh || mesh;
  33848. mesh.subMeshes.push(_this);
  33849. _this._trianglePlanes = [];
  33850. _this._id = mesh.subMeshes.length - 1;
  33851. if (createBoundingBox) {
  33852. _this.refreshBoundingInfo();
  33853. mesh.computeWorldMatrix(true);
  33854. }
  33855. return _this;
  33856. }
  33857. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33858. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33859. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33860. };
  33861. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33862. get: function () {
  33863. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33864. },
  33865. enumerable: true,
  33866. configurable: true
  33867. });
  33868. /**
  33869. * Returns the submesh BoudingInfo object.
  33870. */
  33871. SubMesh.prototype.getBoundingInfo = function () {
  33872. if (this.IsGlobal) {
  33873. return this._mesh.getBoundingInfo();
  33874. }
  33875. return this._boundingInfo;
  33876. };
  33877. /**
  33878. * Sets the submesh BoundingInfo.
  33879. * Return the SubMesh.
  33880. */
  33881. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33882. this._boundingInfo = boundingInfo;
  33883. return this;
  33884. };
  33885. /**
  33886. * Returns the mesh of the current submesh.
  33887. */
  33888. SubMesh.prototype.getMesh = function () {
  33889. return this._mesh;
  33890. };
  33891. /**
  33892. * Returns the rendering mesh of the submesh.
  33893. */
  33894. SubMesh.prototype.getRenderingMesh = function () {
  33895. return this._renderingMesh;
  33896. };
  33897. /**
  33898. * Returns the submesh material.
  33899. */
  33900. SubMesh.prototype.getMaterial = function () {
  33901. var rootMaterial = this._renderingMesh.material;
  33902. if (rootMaterial === null || rootMaterial === undefined) {
  33903. return this._mesh.getScene().defaultMaterial;
  33904. }
  33905. else if (rootMaterial.getSubMaterial) {
  33906. var multiMaterial = rootMaterial;
  33907. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33908. if (this._currentMaterial !== effectiveMaterial) {
  33909. this._currentMaterial = effectiveMaterial;
  33910. this._materialDefines = null;
  33911. }
  33912. return effectiveMaterial;
  33913. }
  33914. return rootMaterial;
  33915. };
  33916. // Methods
  33917. /**
  33918. * Sets a new updated BoundingInfo object to the submesh.
  33919. * Returns the SubMesh.
  33920. */
  33921. SubMesh.prototype.refreshBoundingInfo = function () {
  33922. this._lastColliderWorldVertices = null;
  33923. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33924. return this;
  33925. }
  33926. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33927. if (!data) {
  33928. this._boundingInfo = this._mesh.getBoundingInfo();
  33929. return this;
  33930. }
  33931. var indices = this._renderingMesh.getIndices();
  33932. var extend;
  33933. //is this the only submesh?
  33934. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33935. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33936. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33937. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33938. }
  33939. else {
  33940. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33941. }
  33942. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33943. return this;
  33944. };
  33945. SubMesh.prototype._checkCollision = function (collider) {
  33946. var boundingInfo = this.getBoundingInfo();
  33947. return boundingInfo._checkCollision(collider);
  33948. };
  33949. /**
  33950. * Updates the submesh BoundingInfo.
  33951. * Returns the Submesh.
  33952. */
  33953. SubMesh.prototype.updateBoundingInfo = function (world) {
  33954. var boundingInfo = this.getBoundingInfo();
  33955. if (!boundingInfo) {
  33956. this.refreshBoundingInfo();
  33957. boundingInfo = this.getBoundingInfo();
  33958. }
  33959. boundingInfo.update(world);
  33960. return this;
  33961. };
  33962. /**
  33963. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33964. * Boolean returned.
  33965. */
  33966. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33967. var boundingInfo = this.getBoundingInfo();
  33968. if (!boundingInfo) {
  33969. return false;
  33970. }
  33971. return boundingInfo.isInFrustum(frustumPlanes);
  33972. };
  33973. /**
  33974. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33975. * Boolean returned.
  33976. */
  33977. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33978. var boundingInfo = this.getBoundingInfo();
  33979. if (!boundingInfo) {
  33980. return false;
  33981. }
  33982. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33983. };
  33984. /**
  33985. * Renders the submesh.
  33986. * Returns it.
  33987. */
  33988. SubMesh.prototype.render = function (enableAlphaMode) {
  33989. this._renderingMesh.render(this, enableAlphaMode);
  33990. return this;
  33991. };
  33992. /**
  33993. * Returns a new Index Buffer.
  33994. * Type returned : WebGLBuffer.
  33995. */
  33996. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33997. if (!this._linesIndexBuffer) {
  33998. var linesIndices = [];
  33999. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34000. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34001. }
  34002. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34003. this.linesIndexCount = linesIndices.length;
  34004. }
  34005. return this._linesIndexBuffer;
  34006. };
  34007. /**
  34008. * True is the passed Ray intersects the submesh bounding box.
  34009. * Boolean returned.
  34010. */
  34011. SubMesh.prototype.canIntersects = function (ray) {
  34012. var boundingInfo = this.getBoundingInfo();
  34013. if (!boundingInfo) {
  34014. return false;
  34015. }
  34016. return ray.intersectsBox(boundingInfo.boundingBox);
  34017. };
  34018. /**
  34019. * Returns an object IntersectionInfo.
  34020. */
  34021. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34022. var intersectInfo = null;
  34023. var material = this.getMaterial();
  34024. if (!material) {
  34025. return null;
  34026. }
  34027. switch (material.fillMode) {
  34028. case BABYLON.Material.PointListDrawMode:
  34029. case BABYLON.Material.LineListDrawMode:
  34030. case BABYLON.Material.LineLoopDrawMode:
  34031. case BABYLON.Material.LineStripDrawMode:
  34032. case BABYLON.Material.TriangleFanDrawMode:
  34033. case BABYLON.Material.TriangleStripDrawMode:
  34034. return null;
  34035. }
  34036. // LineMesh first as it's also a Mesh...
  34037. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34038. var lineMesh = this._mesh;
  34039. // Line test
  34040. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34041. var p0 = positions[indices[index]];
  34042. var p1 = positions[indices[index + 1]];
  34043. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34044. if (length < 0) {
  34045. continue;
  34046. }
  34047. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34048. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34049. if (fastCheck) {
  34050. break;
  34051. }
  34052. }
  34053. }
  34054. }
  34055. else {
  34056. // Triangles test
  34057. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34058. var p0 = positions[indices[index]];
  34059. var p1 = positions[indices[index + 1]];
  34060. var p2 = positions[indices[index + 2]];
  34061. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34062. if (currentIntersectInfo) {
  34063. if (currentIntersectInfo.distance < 0) {
  34064. continue;
  34065. }
  34066. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34067. intersectInfo = currentIntersectInfo;
  34068. intersectInfo.faceId = index / 3;
  34069. if (fastCheck) {
  34070. break;
  34071. }
  34072. }
  34073. }
  34074. }
  34075. }
  34076. return intersectInfo;
  34077. };
  34078. SubMesh.prototype._rebuild = function () {
  34079. if (this._linesIndexBuffer) {
  34080. this._linesIndexBuffer = null;
  34081. }
  34082. };
  34083. // Clone
  34084. /**
  34085. * Creates a new Submesh from the passed Mesh.
  34086. */
  34087. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34088. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34089. if (!this.IsGlobal) {
  34090. var boundingInfo = this.getBoundingInfo();
  34091. if (!boundingInfo) {
  34092. return result;
  34093. }
  34094. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34095. }
  34096. return result;
  34097. };
  34098. // Dispose
  34099. /**
  34100. * Disposes the Submesh.
  34101. * Returns nothing.
  34102. */
  34103. SubMesh.prototype.dispose = function () {
  34104. if (this._linesIndexBuffer) {
  34105. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34106. this._linesIndexBuffer = null;
  34107. }
  34108. // Remove from mesh
  34109. var index = this._mesh.subMeshes.indexOf(this);
  34110. this._mesh.subMeshes.splice(index, 1);
  34111. };
  34112. // Statics
  34113. /**
  34114. * Creates a new Submesh from the passed parameters :
  34115. * - materialIndex (integer) : the index of the main mesh material.
  34116. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34117. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34118. * - mesh (Mesh) : the main mesh to create the submesh from.
  34119. * - renderingMesh (optional Mesh) : rendering mesh.
  34120. */
  34121. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34122. var minVertexIndex = Number.MAX_VALUE;
  34123. var maxVertexIndex = -Number.MAX_VALUE;
  34124. renderingMesh = (renderingMesh || mesh);
  34125. var indices = renderingMesh.getIndices();
  34126. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34127. var vertexIndex = indices[index];
  34128. if (vertexIndex < minVertexIndex)
  34129. minVertexIndex = vertexIndex;
  34130. if (vertexIndex > maxVertexIndex)
  34131. maxVertexIndex = vertexIndex;
  34132. }
  34133. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34134. };
  34135. return SubMesh;
  34136. }(BaseSubMesh));
  34137. BABYLON.SubMesh = SubMesh;
  34138. })(BABYLON || (BABYLON = {}));
  34139. //# sourceMappingURL=babylon.subMesh.js.map
  34140. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34141. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34142. s = arguments[i];
  34143. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34144. t[p] = s[p];
  34145. }
  34146. return t;
  34147. };
  34148. var BABYLON;
  34149. (function (BABYLON) {
  34150. /**
  34151. * Manages the defines for the Material
  34152. */
  34153. var MaterialDefines = /** @class */ (function () {
  34154. function MaterialDefines() {
  34155. this._isDirty = true;
  34156. /** @hidden */
  34157. this._areLightsDirty = true;
  34158. /** @hidden */
  34159. this._areAttributesDirty = true;
  34160. /** @hidden */
  34161. this._areTexturesDirty = true;
  34162. /** @hidden */
  34163. this._areFresnelDirty = true;
  34164. /** @hidden */
  34165. this._areMiscDirty = true;
  34166. /** @hidden */
  34167. this._areImageProcessingDirty = true;
  34168. /** @hidden */
  34169. this._normals = false;
  34170. /** @hidden */
  34171. this._uvs = false;
  34172. /** @hidden */
  34173. this._needNormals = false;
  34174. /** @hidden */
  34175. this._needUVs = false;
  34176. }
  34177. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34178. /**
  34179. * Specifies if the material needs to be re-calculated
  34180. */
  34181. get: function () {
  34182. return this._isDirty;
  34183. },
  34184. enumerable: true,
  34185. configurable: true
  34186. });
  34187. /**
  34188. * Marks the material to indicate that it has been re-calculated
  34189. */
  34190. MaterialDefines.prototype.markAsProcessed = function () {
  34191. this._isDirty = false;
  34192. this._areAttributesDirty = false;
  34193. this._areTexturesDirty = false;
  34194. this._areFresnelDirty = false;
  34195. this._areLightsDirty = false;
  34196. this._areMiscDirty = false;
  34197. this._areImageProcessingDirty = false;
  34198. };
  34199. /**
  34200. * Marks the material to indicate that it needs to be re-calculated
  34201. */
  34202. MaterialDefines.prototype.markAsUnprocessed = function () {
  34203. this._isDirty = true;
  34204. };
  34205. /**
  34206. * Marks the material to indicate all of its defines need to be re-calculated
  34207. */
  34208. MaterialDefines.prototype.markAllAsDirty = function () {
  34209. this._areTexturesDirty = true;
  34210. this._areAttributesDirty = true;
  34211. this._areLightsDirty = true;
  34212. this._areFresnelDirty = true;
  34213. this._areMiscDirty = true;
  34214. this._areImageProcessingDirty = true;
  34215. this._isDirty = true;
  34216. };
  34217. /**
  34218. * Marks the material to indicate that image processing needs to be re-calculated
  34219. */
  34220. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34221. this._areImageProcessingDirty = true;
  34222. this._isDirty = true;
  34223. };
  34224. /**
  34225. * Marks the material to indicate the lights need to be re-calculated
  34226. */
  34227. MaterialDefines.prototype.markAsLightDirty = function () {
  34228. this._areLightsDirty = true;
  34229. this._isDirty = true;
  34230. };
  34231. /**
  34232. * Marks the attribute state as changed
  34233. */
  34234. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34235. this._areAttributesDirty = true;
  34236. this._isDirty = true;
  34237. };
  34238. /**
  34239. * Marks the texture state as changed
  34240. */
  34241. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34242. this._areTexturesDirty = true;
  34243. this._isDirty = true;
  34244. };
  34245. /**
  34246. * Marks the fresnel state as changed
  34247. */
  34248. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34249. this._areFresnelDirty = true;
  34250. this._isDirty = true;
  34251. };
  34252. /**
  34253. * Marks the misc state as changed
  34254. */
  34255. MaterialDefines.prototype.markAsMiscDirty = function () {
  34256. this._areMiscDirty = true;
  34257. this._isDirty = true;
  34258. };
  34259. /**
  34260. * Rebuilds the material defines
  34261. */
  34262. MaterialDefines.prototype.rebuild = function () {
  34263. if (this._keys) {
  34264. delete this._keys;
  34265. }
  34266. this._keys = [];
  34267. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34268. var key = _a[_i];
  34269. if (key[0] === "_") {
  34270. continue;
  34271. }
  34272. this._keys.push(key);
  34273. }
  34274. };
  34275. /**
  34276. * Specifies if two material defines are equal
  34277. * @param other - A material define instance to compare to
  34278. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34279. */
  34280. MaterialDefines.prototype.isEqual = function (other) {
  34281. if (this._keys.length !== other._keys.length) {
  34282. return false;
  34283. }
  34284. for (var index = 0; index < this._keys.length; index++) {
  34285. var prop = this._keys[index];
  34286. if (this[prop] !== other[prop]) {
  34287. return false;
  34288. }
  34289. }
  34290. return true;
  34291. };
  34292. /**
  34293. * Clones this instance's defines to another instance
  34294. * @param other - material defines to clone values to
  34295. */
  34296. MaterialDefines.prototype.cloneTo = function (other) {
  34297. if (this._keys.length !== other._keys.length) {
  34298. other._keys = this._keys.slice(0);
  34299. }
  34300. for (var index = 0; index < this._keys.length; index++) {
  34301. var prop = this._keys[index];
  34302. other[prop] = this[prop];
  34303. }
  34304. };
  34305. /**
  34306. * Resets the material define values
  34307. */
  34308. MaterialDefines.prototype.reset = function () {
  34309. for (var index = 0; index < this._keys.length; index++) {
  34310. var prop = this._keys[index];
  34311. var type = typeof this[prop];
  34312. switch (type) {
  34313. case "number":
  34314. this[prop] = 0;
  34315. break;
  34316. case "string":
  34317. this[prop] = "";
  34318. break;
  34319. default:
  34320. this[prop] = false;
  34321. break;
  34322. }
  34323. }
  34324. };
  34325. /**
  34326. * Converts the material define values to a string
  34327. * @returns - String of material define information
  34328. */
  34329. MaterialDefines.prototype.toString = function () {
  34330. var result = "";
  34331. for (var index = 0; index < this._keys.length; index++) {
  34332. var prop = this._keys[index];
  34333. var value = this[prop];
  34334. var type = typeof value;
  34335. switch (type) {
  34336. case "number":
  34337. case "string":
  34338. result += "#define " + prop + " " + value + "\n";
  34339. break;
  34340. default:
  34341. if (value) {
  34342. result += "#define " + prop + "\n";
  34343. }
  34344. break;
  34345. }
  34346. }
  34347. return result;
  34348. };
  34349. return MaterialDefines;
  34350. }());
  34351. BABYLON.MaterialDefines = MaterialDefines;
  34352. /**
  34353. * Base class for the main features of a material in Babylon.js
  34354. */
  34355. var Material = /** @class */ (function () {
  34356. /**
  34357. * Creates a material instance
  34358. * @param name defines the name of the material
  34359. * @param scene defines the scene to reference
  34360. * @param doNotAdd specifies if the material should be added to the scene
  34361. */
  34362. function Material(name, scene, doNotAdd) {
  34363. /**
  34364. * Specifies if the ready state should be checked on each call
  34365. */
  34366. this.checkReadyOnEveryCall = false;
  34367. /**
  34368. * Specifies if the ready state should be checked once
  34369. */
  34370. this.checkReadyOnlyOnce = false;
  34371. /**
  34372. * The state of the material
  34373. */
  34374. this.state = "";
  34375. /**
  34376. * The alpha value of the material
  34377. */
  34378. this._alpha = 1.0;
  34379. /**
  34380. * Specifies if back face culling is enabled
  34381. */
  34382. this._backFaceCulling = true;
  34383. /**
  34384. * Specifies if the material should be serialized
  34385. */
  34386. this.doNotSerialize = false;
  34387. /**
  34388. * Specifies if the effect should be stored on sub meshes
  34389. */
  34390. this.storeEffectOnSubMeshes = false;
  34391. /**
  34392. * An event triggered when the material is disposed
  34393. */
  34394. this.onDisposeObservable = new BABYLON.Observable();
  34395. /**
  34396. * An event triggered when the material is bound
  34397. */
  34398. this.onBindObservable = new BABYLON.Observable();
  34399. /**
  34400. * An event triggered when the material is unbound
  34401. */
  34402. this.onUnBindObservable = new BABYLON.Observable();
  34403. /**
  34404. * Stores the value of the alpha mode
  34405. */
  34406. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34407. /**
  34408. * Stores the state of the need depth pre-pass value
  34409. */
  34410. this._needDepthPrePass = false;
  34411. /**
  34412. * Specifies if depth writing should be disabled
  34413. */
  34414. this.disableDepthWrite = false;
  34415. /**
  34416. * Specifies if depth writing should be forced
  34417. */
  34418. this.forceDepthWrite = false;
  34419. /**
  34420. * Specifies if there should be a separate pass for culling
  34421. */
  34422. this.separateCullingPass = false;
  34423. /**
  34424. * Stores the state specifing if fog should be enabled
  34425. */
  34426. this._fogEnabled = true;
  34427. /**
  34428. * Stores the size of points
  34429. */
  34430. this.pointSize = 1.0;
  34431. /**
  34432. * Stores the z offset value
  34433. */
  34434. this.zOffset = 0;
  34435. /**
  34436. * Specifies if the material was previously ready
  34437. */
  34438. this._wasPreviouslyReady = false;
  34439. /**
  34440. * Stores the fill mode state
  34441. */
  34442. this._fillMode = Material.TriangleFillMode;
  34443. this.name = name;
  34444. this.id = name || BABYLON.Tools.RandomId();
  34445. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34446. if (this._scene.useRightHandedSystem) {
  34447. this.sideOrientation = Material.ClockWiseSideOrientation;
  34448. }
  34449. else {
  34450. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34451. }
  34452. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34453. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34454. if (!doNotAdd) {
  34455. this._scene.materials.push(this);
  34456. }
  34457. }
  34458. Object.defineProperty(Material, "TriangleFillMode", {
  34459. /**
  34460. * Returns the triangle fill mode
  34461. */
  34462. get: function () {
  34463. return Material._TriangleFillMode;
  34464. },
  34465. enumerable: true,
  34466. configurable: true
  34467. });
  34468. Object.defineProperty(Material, "WireFrameFillMode", {
  34469. /**
  34470. * Returns the wireframe mode
  34471. */
  34472. get: function () {
  34473. return Material._WireFrameFillMode;
  34474. },
  34475. enumerable: true,
  34476. configurable: true
  34477. });
  34478. Object.defineProperty(Material, "PointFillMode", {
  34479. /**
  34480. * Returns the point fill mode
  34481. */
  34482. get: function () {
  34483. return Material._PointFillMode;
  34484. },
  34485. enumerable: true,
  34486. configurable: true
  34487. });
  34488. Object.defineProperty(Material, "PointListDrawMode", {
  34489. /**
  34490. * Returns the point list draw mode
  34491. */
  34492. get: function () {
  34493. return Material._PointListDrawMode;
  34494. },
  34495. enumerable: true,
  34496. configurable: true
  34497. });
  34498. Object.defineProperty(Material, "LineListDrawMode", {
  34499. /**
  34500. * Returns the line list draw mode
  34501. */
  34502. get: function () {
  34503. return Material._LineListDrawMode;
  34504. },
  34505. enumerable: true,
  34506. configurable: true
  34507. });
  34508. Object.defineProperty(Material, "LineLoopDrawMode", {
  34509. /**
  34510. * Returns the line loop draw mode
  34511. */
  34512. get: function () {
  34513. return Material._LineLoopDrawMode;
  34514. },
  34515. enumerable: true,
  34516. configurable: true
  34517. });
  34518. Object.defineProperty(Material, "LineStripDrawMode", {
  34519. /**
  34520. * Returns the line strip draw mode
  34521. */
  34522. get: function () {
  34523. return Material._LineStripDrawMode;
  34524. },
  34525. enumerable: true,
  34526. configurable: true
  34527. });
  34528. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34529. /**
  34530. * Returns the triangle strip draw mode
  34531. */
  34532. get: function () {
  34533. return Material._TriangleStripDrawMode;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34539. /**
  34540. * Returns the triangle fan draw mode
  34541. */
  34542. get: function () {
  34543. return Material._TriangleFanDrawMode;
  34544. },
  34545. enumerable: true,
  34546. configurable: true
  34547. });
  34548. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34549. /**
  34550. * Returns the clock-wise side orientation
  34551. */
  34552. get: function () {
  34553. return Material._ClockWiseSideOrientation;
  34554. },
  34555. enumerable: true,
  34556. configurable: true
  34557. });
  34558. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34559. /**
  34560. * Returns the counter clock-wise side orientation
  34561. */
  34562. get: function () {
  34563. return Material._CounterClockWiseSideOrientation;
  34564. },
  34565. enumerable: true,
  34566. configurable: true
  34567. });
  34568. Object.defineProperty(Material, "TextureDirtyFlag", {
  34569. /**
  34570. * Returns the dirty texture flag value
  34571. */
  34572. get: function () {
  34573. return Material._TextureDirtyFlag;
  34574. },
  34575. enumerable: true,
  34576. configurable: true
  34577. });
  34578. Object.defineProperty(Material, "LightDirtyFlag", {
  34579. /**
  34580. * Returns the dirty light flag value
  34581. */
  34582. get: function () {
  34583. return Material._LightDirtyFlag;
  34584. },
  34585. enumerable: true,
  34586. configurable: true
  34587. });
  34588. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34589. /**
  34590. * Returns the dirty fresnel flag value
  34591. */
  34592. get: function () {
  34593. return Material._FresnelDirtyFlag;
  34594. },
  34595. enumerable: true,
  34596. configurable: true
  34597. });
  34598. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34599. /**
  34600. * Returns the dirty attributes flag value
  34601. */
  34602. get: function () {
  34603. return Material._AttributesDirtyFlag;
  34604. },
  34605. enumerable: true,
  34606. configurable: true
  34607. });
  34608. Object.defineProperty(Material, "MiscDirtyFlag", {
  34609. /**
  34610. * Returns the dirty misc flag value
  34611. */
  34612. get: function () {
  34613. return Material._MiscDirtyFlag;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. Object.defineProperty(Material.prototype, "alpha", {
  34619. /**
  34620. * Gets the alpha value of the material
  34621. */
  34622. get: function () {
  34623. return this._alpha;
  34624. },
  34625. /**
  34626. * Sets the alpha value of the material
  34627. */
  34628. set: function (value) {
  34629. if (this._alpha === value) {
  34630. return;
  34631. }
  34632. this._alpha = value;
  34633. this.markAsDirty(Material.MiscDirtyFlag);
  34634. },
  34635. enumerable: true,
  34636. configurable: true
  34637. });
  34638. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34639. /**
  34640. * Gets the back-face culling state
  34641. */
  34642. get: function () {
  34643. return this._backFaceCulling;
  34644. },
  34645. /**
  34646. * Sets the back-face culling state
  34647. */
  34648. set: function (value) {
  34649. if (this._backFaceCulling === value) {
  34650. return;
  34651. }
  34652. this._backFaceCulling = value;
  34653. this.markAsDirty(Material.TextureDirtyFlag);
  34654. },
  34655. enumerable: true,
  34656. configurable: true
  34657. });
  34658. Object.defineProperty(Material.prototype, "onDispose", {
  34659. /**
  34660. * Called during a dispose event
  34661. */
  34662. set: function (callback) {
  34663. if (this._onDisposeObserver) {
  34664. this.onDisposeObservable.remove(this._onDisposeObserver);
  34665. }
  34666. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34667. },
  34668. enumerable: true,
  34669. configurable: true
  34670. });
  34671. Object.defineProperty(Material.prototype, "onBind", {
  34672. /**
  34673. * Called during a bind event
  34674. */
  34675. set: function (callback) {
  34676. if (this._onBindObserver) {
  34677. this.onBindObservable.remove(this._onBindObserver);
  34678. }
  34679. this._onBindObserver = this.onBindObservable.add(callback);
  34680. },
  34681. enumerable: true,
  34682. configurable: true
  34683. });
  34684. Object.defineProperty(Material.prototype, "alphaMode", {
  34685. /**
  34686. * Gets the value of the alpha mode
  34687. */
  34688. get: function () {
  34689. return this._alphaMode;
  34690. },
  34691. /**
  34692. * Sets the value of the alpha mode.
  34693. *
  34694. * | Value | Type | Description |
  34695. * | --- | --- | --- |
  34696. * | 0 | ALPHA_DISABLE | |
  34697. * | 1 | ALPHA_ADD | |
  34698. * | 2 | ALPHA_COMBINE | |
  34699. * | 3 | ALPHA_SUBTRACT | |
  34700. * | 4 | ALPHA_MULTIPLY | |
  34701. * | 5 | ALPHA_MAXIMIZED | |
  34702. * | 6 | ALPHA_ONEONE | |
  34703. * | 7 | ALPHA_PREMULTIPLIED | |
  34704. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34705. * | 9 | ALPHA_INTERPOLATE | |
  34706. * | 10 | ALPHA_SCREENMODE | |
  34707. *
  34708. */
  34709. set: function (value) {
  34710. if (this._alphaMode === value) {
  34711. return;
  34712. }
  34713. this._alphaMode = value;
  34714. this.markAsDirty(Material.TextureDirtyFlag);
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34720. /**
  34721. * Gets the depth pre-pass value
  34722. */
  34723. get: function () {
  34724. return this._needDepthPrePass;
  34725. },
  34726. /**
  34727. * Sets the need depth pre-pass value
  34728. */
  34729. set: function (value) {
  34730. if (this._needDepthPrePass === value) {
  34731. return;
  34732. }
  34733. this._needDepthPrePass = value;
  34734. if (this._needDepthPrePass) {
  34735. this.checkReadyOnEveryCall = true;
  34736. }
  34737. },
  34738. enumerable: true,
  34739. configurable: true
  34740. });
  34741. Object.defineProperty(Material.prototype, "fogEnabled", {
  34742. /**
  34743. * Gets the value of the fog enabled state
  34744. */
  34745. get: function () {
  34746. return this._fogEnabled;
  34747. },
  34748. /**
  34749. * Sets the state for enabling fog
  34750. */
  34751. set: function (value) {
  34752. if (this._fogEnabled === value) {
  34753. return;
  34754. }
  34755. this._fogEnabled = value;
  34756. this.markAsDirty(Material.MiscDirtyFlag);
  34757. },
  34758. enumerable: true,
  34759. configurable: true
  34760. });
  34761. Object.defineProperty(Material.prototype, "wireframe", {
  34762. /**
  34763. * Gets a value specifying if wireframe mode is enabled
  34764. */
  34765. get: function () {
  34766. switch (this._fillMode) {
  34767. case Material.WireFrameFillMode:
  34768. case Material.LineListDrawMode:
  34769. case Material.LineLoopDrawMode:
  34770. case Material.LineStripDrawMode:
  34771. return true;
  34772. }
  34773. return this._scene.forceWireframe;
  34774. },
  34775. /**
  34776. * Sets the state of wireframe mode
  34777. */
  34778. set: function (value) {
  34779. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34780. },
  34781. enumerable: true,
  34782. configurable: true
  34783. });
  34784. Object.defineProperty(Material.prototype, "pointsCloud", {
  34785. /**
  34786. * Gets the value specifying if point clouds are enabled
  34787. */
  34788. get: function () {
  34789. switch (this._fillMode) {
  34790. case Material.PointFillMode:
  34791. case Material.PointListDrawMode:
  34792. return true;
  34793. }
  34794. return this._scene.forcePointsCloud;
  34795. },
  34796. /**
  34797. * Sets the state of point cloud mode
  34798. */
  34799. set: function (value) {
  34800. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34801. },
  34802. enumerable: true,
  34803. configurable: true
  34804. });
  34805. Object.defineProperty(Material.prototype, "fillMode", {
  34806. /**
  34807. * Gets the material fill mode
  34808. */
  34809. get: function () {
  34810. return this._fillMode;
  34811. },
  34812. /**
  34813. * Sets the material fill mode
  34814. */
  34815. set: function (value) {
  34816. if (this._fillMode === value) {
  34817. return;
  34818. }
  34819. this._fillMode = value;
  34820. this.markAsDirty(Material.MiscDirtyFlag);
  34821. },
  34822. enumerable: true,
  34823. configurable: true
  34824. });
  34825. /**
  34826. * Returns a string representation of the current material
  34827. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34828. * @returns a string with material information
  34829. */
  34830. Material.prototype.toString = function (fullDetails) {
  34831. var ret = "Name: " + this.name;
  34832. if (fullDetails) {
  34833. }
  34834. return ret;
  34835. };
  34836. /**
  34837. * Gets the class name of the material
  34838. * @returns a string with the class name of the material
  34839. */
  34840. Material.prototype.getClassName = function () {
  34841. return "Material";
  34842. };
  34843. Object.defineProperty(Material.prototype, "isFrozen", {
  34844. /**
  34845. * Specifies if updates for the material been locked
  34846. */
  34847. get: function () {
  34848. return this.checkReadyOnlyOnce;
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. /**
  34854. * Locks updates for the material
  34855. */
  34856. Material.prototype.freeze = function () {
  34857. this.checkReadyOnlyOnce = true;
  34858. };
  34859. /**
  34860. * Unlocks updates for the material
  34861. */
  34862. Material.prototype.unfreeze = function () {
  34863. this.checkReadyOnlyOnce = false;
  34864. };
  34865. /**
  34866. * Specifies if the material is ready to be used
  34867. * @param mesh defines the mesh to check
  34868. * @param useInstances specifies if instances should be used
  34869. * @returns a boolean indicating if the material is ready to be used
  34870. */
  34871. Material.prototype.isReady = function (mesh, useInstances) {
  34872. return true;
  34873. };
  34874. /**
  34875. * Specifies that the submesh is ready to be used
  34876. * @param mesh defines the mesh to check
  34877. * @param subMesh defines which submesh to check
  34878. * @param useInstances specifies that instances should be used
  34879. * @returns a boolean indicating that the submesh is ready or not
  34880. */
  34881. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34882. return false;
  34883. };
  34884. /**
  34885. * Returns the material effect
  34886. * @returns the effect associated with the material
  34887. */
  34888. Material.prototype.getEffect = function () {
  34889. return this._effect;
  34890. };
  34891. /**
  34892. * Returns the current scene
  34893. * @returns a Scene
  34894. */
  34895. Material.prototype.getScene = function () {
  34896. return this._scene;
  34897. };
  34898. /**
  34899. * Specifies if the material will require alpha blending
  34900. * @returns a boolean specifying if alpha blending is needed
  34901. */
  34902. Material.prototype.needAlphaBlending = function () {
  34903. return (this.alpha < 1.0);
  34904. };
  34905. /**
  34906. * Specifies if the mesh will require alpha blending
  34907. * @param mesh defines the mesh to check
  34908. * @returns a boolean specifying if alpha blending is needed for the mesh
  34909. */
  34910. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34911. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34912. };
  34913. /**
  34914. * Specifies if this material should be rendered in alpha test mode
  34915. * @returns a boolean specifying if an alpha test is needed.
  34916. */
  34917. Material.prototype.needAlphaTesting = function () {
  34918. return false;
  34919. };
  34920. /**
  34921. * Gets the texture used for the alpha test
  34922. * @returns the texture to use for alpha testing
  34923. */
  34924. Material.prototype.getAlphaTestTexture = function () {
  34925. return null;
  34926. };
  34927. /**
  34928. * Marks the material to indicate that it needs to be re-calculated
  34929. */
  34930. Material.prototype.markDirty = function () {
  34931. this._wasPreviouslyReady = false;
  34932. };
  34933. /** @hidden */
  34934. Material.prototype._preBind = function (effect, overrideOrientation) {
  34935. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34936. var engine = this._scene.getEngine();
  34937. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34938. var reverse = orientation === Material.ClockWiseSideOrientation;
  34939. engine.enableEffect(effect ? effect : this._effect);
  34940. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34941. return reverse;
  34942. };
  34943. /**
  34944. * Binds the material to the mesh
  34945. * @param world defines the world transformation matrix
  34946. * @param mesh defines the mesh to bind the material to
  34947. */
  34948. Material.prototype.bind = function (world, mesh) {
  34949. };
  34950. /**
  34951. * Binds the submesh to the material
  34952. * @param world defines the world transformation matrix
  34953. * @param mesh defines the mesh containing the submesh
  34954. * @param subMesh defines the submesh to bind the material to
  34955. */
  34956. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34957. };
  34958. /**
  34959. * Binds the world matrix to the material
  34960. * @param world defines the world transformation matrix
  34961. */
  34962. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34963. };
  34964. /**
  34965. * Binds the scene's uniform buffer to the effect.
  34966. * @param effect defines the effect to bind to the scene uniform buffer
  34967. * @param sceneUbo defines the uniform buffer storing scene data
  34968. */
  34969. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34970. sceneUbo.bindToEffect(effect, "Scene");
  34971. };
  34972. /**
  34973. * Binds the view matrix to the effect
  34974. * @param effect defines the effect to bind the view matrix to
  34975. */
  34976. Material.prototype.bindView = function (effect) {
  34977. if (!this._useUBO) {
  34978. effect.setMatrix("view", this.getScene().getViewMatrix());
  34979. }
  34980. else {
  34981. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34982. }
  34983. };
  34984. /**
  34985. * Binds the view projection matrix to the effect
  34986. * @param effect defines the effect to bind the view projection matrix to
  34987. */
  34988. Material.prototype.bindViewProjection = function (effect) {
  34989. if (!this._useUBO) {
  34990. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34991. }
  34992. else {
  34993. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34994. }
  34995. };
  34996. /**
  34997. * Specifies if material alpha testing should be turned on for the mesh
  34998. * @param mesh defines the mesh to check
  34999. */
  35000. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35001. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35002. };
  35003. /**
  35004. * Processes to execute after binding the material to a mesh
  35005. * @param mesh defines the rendered mesh
  35006. */
  35007. Material.prototype._afterBind = function (mesh) {
  35008. this._scene._cachedMaterial = this;
  35009. if (mesh) {
  35010. this._scene._cachedVisibility = mesh.visibility;
  35011. }
  35012. else {
  35013. this._scene._cachedVisibility = 1;
  35014. }
  35015. if (mesh) {
  35016. this.onBindObservable.notifyObservers(mesh);
  35017. }
  35018. if (this.disableDepthWrite) {
  35019. var engine = this._scene.getEngine();
  35020. this._cachedDepthWriteState = engine.getDepthWrite();
  35021. engine.setDepthWrite(false);
  35022. }
  35023. };
  35024. /**
  35025. * Unbinds the material from the mesh
  35026. */
  35027. Material.prototype.unbind = function () {
  35028. this.onUnBindObservable.notifyObservers(this);
  35029. if (this.disableDepthWrite) {
  35030. var engine = this._scene.getEngine();
  35031. engine.setDepthWrite(this._cachedDepthWriteState);
  35032. }
  35033. };
  35034. /**
  35035. * Gets the active textures from the material
  35036. * @returns an array of textures
  35037. */
  35038. Material.prototype.getActiveTextures = function () {
  35039. return [];
  35040. };
  35041. /**
  35042. * Specifies if the material uses a texture
  35043. * @param texture defines the texture to check against the material
  35044. * @returns a boolean specifying if the material uses the texture
  35045. */
  35046. Material.prototype.hasTexture = function (texture) {
  35047. return false;
  35048. };
  35049. /**
  35050. * Makes a duplicate of the material, and gives it a new name
  35051. * @param name defines the new name for the duplicated material
  35052. * @returns the cloned material
  35053. */
  35054. Material.prototype.clone = function (name) {
  35055. return null;
  35056. };
  35057. /**
  35058. * Gets the meshes bound to the material
  35059. * @returns an array of meshes bound to the material
  35060. */
  35061. Material.prototype.getBindedMeshes = function () {
  35062. var result = new Array();
  35063. for (var index = 0; index < this._scene.meshes.length; index++) {
  35064. var mesh = this._scene.meshes[index];
  35065. if (mesh.material === this) {
  35066. result.push(mesh);
  35067. }
  35068. }
  35069. return result;
  35070. };
  35071. /**
  35072. * Force shader compilation
  35073. * @param mesh defines the mesh associated with this material
  35074. * @param onCompiled defines a function to execute once the material is compiled
  35075. * @param options defines the options to configure the compilation
  35076. */
  35077. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35078. var _this = this;
  35079. var localOptions = __assign({ clipPlane: false }, options);
  35080. var subMesh = new BABYLON.BaseSubMesh();
  35081. var scene = this.getScene();
  35082. var checkReady = function () {
  35083. if (!_this._scene || !_this._scene.getEngine()) {
  35084. return;
  35085. }
  35086. if (subMesh._materialDefines) {
  35087. subMesh._materialDefines._renderId = -1;
  35088. }
  35089. var clipPlaneState = scene.clipPlane;
  35090. if (localOptions.clipPlane) {
  35091. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35092. }
  35093. if (_this.storeEffectOnSubMeshes) {
  35094. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35095. if (onCompiled) {
  35096. onCompiled(_this);
  35097. }
  35098. }
  35099. else {
  35100. setTimeout(checkReady, 16);
  35101. }
  35102. }
  35103. else {
  35104. if (_this.isReady(mesh)) {
  35105. if (onCompiled) {
  35106. onCompiled(_this);
  35107. }
  35108. }
  35109. else {
  35110. setTimeout(checkReady, 16);
  35111. }
  35112. }
  35113. if (localOptions.clipPlane) {
  35114. scene.clipPlane = clipPlaneState;
  35115. }
  35116. };
  35117. checkReady();
  35118. };
  35119. /**
  35120. * Force shader compilation
  35121. * @param mesh defines the mesh that will use this material
  35122. * @param options defines additional options for compiling the shaders
  35123. * @returns a promise that resolves when the compilation completes
  35124. */
  35125. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35126. var _this = this;
  35127. return new Promise(function (resolve) {
  35128. _this.forceCompilation(mesh, function () {
  35129. resolve();
  35130. }, options);
  35131. });
  35132. };
  35133. /**
  35134. * Marks a define in the material to indicate that it needs to be re-computed
  35135. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35136. */
  35137. Material.prototype.markAsDirty = function (flag) {
  35138. if (flag & Material.TextureDirtyFlag) {
  35139. this._markAllSubMeshesAsTexturesDirty();
  35140. }
  35141. if (flag & Material.LightDirtyFlag) {
  35142. this._markAllSubMeshesAsLightsDirty();
  35143. }
  35144. if (flag & Material.FresnelDirtyFlag) {
  35145. this._markAllSubMeshesAsFresnelDirty();
  35146. }
  35147. if (flag & Material.AttributesDirtyFlag) {
  35148. this._markAllSubMeshesAsAttributesDirty();
  35149. }
  35150. if (flag & Material.MiscDirtyFlag) {
  35151. this._markAllSubMeshesAsMiscDirty();
  35152. }
  35153. this.getScene().resetCachedMaterial();
  35154. };
  35155. /**
  35156. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35157. * @param func defines a function which checks material defines against the submeshes
  35158. */
  35159. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35160. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35161. var mesh = _a[_i];
  35162. if (!mesh.subMeshes) {
  35163. continue;
  35164. }
  35165. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35166. var subMesh = _c[_b];
  35167. if (subMesh.getMaterial() !== this) {
  35168. continue;
  35169. }
  35170. if (!subMesh._materialDefines) {
  35171. continue;
  35172. }
  35173. func(subMesh._materialDefines);
  35174. }
  35175. }
  35176. };
  35177. /**
  35178. * Indicates that image processing needs to be re-calculated for all submeshes
  35179. */
  35180. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35181. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35182. };
  35183. /**
  35184. * Indicates that textures need to be re-calculated for all submeshes
  35185. */
  35186. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35187. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35188. };
  35189. /**
  35190. * Indicates that fresnel needs to be re-calculated for all submeshes
  35191. */
  35192. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35193. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35194. };
  35195. /**
  35196. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35197. */
  35198. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35199. this._markAllSubMeshesAsDirty(function (defines) {
  35200. defines.markAsFresnelDirty();
  35201. defines.markAsMiscDirty();
  35202. });
  35203. };
  35204. /**
  35205. * Indicates that lights need to be re-calculated for all submeshes
  35206. */
  35207. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35208. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35209. };
  35210. /**
  35211. * Indicates that attributes need to be re-calculated for all submeshes
  35212. */
  35213. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35214. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35215. };
  35216. /**
  35217. * Indicates that misc needs to be re-calculated for all submeshes
  35218. */
  35219. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35220. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35221. };
  35222. /**
  35223. * Indicates that textures and misc need to be re-calculated for all submeshes
  35224. */
  35225. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35226. this._markAllSubMeshesAsDirty(function (defines) {
  35227. defines.markAsTexturesDirty();
  35228. defines.markAsMiscDirty();
  35229. });
  35230. };
  35231. /**
  35232. * Disposes the material
  35233. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35234. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35235. */
  35236. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35237. // Animations
  35238. this.getScene().stopAnimation(this);
  35239. this.getScene().freeProcessedMaterials();
  35240. // Remove from scene
  35241. var index = this._scene.materials.indexOf(this);
  35242. if (index >= 0) {
  35243. this._scene.materials.splice(index, 1);
  35244. }
  35245. // Remove from meshes
  35246. for (index = 0; index < this._scene.meshes.length; index++) {
  35247. var mesh = this._scene.meshes[index];
  35248. if (mesh.material === this) {
  35249. mesh.material = null;
  35250. if (mesh.geometry) {
  35251. var geometry = (mesh.geometry);
  35252. if (this.storeEffectOnSubMeshes) {
  35253. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35254. var subMesh = _a[_i];
  35255. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35256. if (forceDisposeEffect && subMesh._materialEffect) {
  35257. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35258. }
  35259. }
  35260. }
  35261. else {
  35262. geometry._releaseVertexArrayObject(this._effect);
  35263. }
  35264. }
  35265. }
  35266. }
  35267. this._uniformBuffer.dispose();
  35268. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35269. if (forceDisposeEffect && this._effect) {
  35270. if (!this.storeEffectOnSubMeshes) {
  35271. this._scene.getEngine()._releaseEffect(this._effect);
  35272. }
  35273. this._effect = null;
  35274. }
  35275. // Callback
  35276. this.onDisposeObservable.notifyObservers(this);
  35277. this.onDisposeObservable.clear();
  35278. this.onBindObservable.clear();
  35279. this.onUnBindObservable.clear();
  35280. };
  35281. /**
  35282. * Serializes this material
  35283. * @returns the serialized material object
  35284. */
  35285. Material.prototype.serialize = function () {
  35286. return BABYLON.SerializationHelper.Serialize(this);
  35287. };
  35288. /**
  35289. * Creates a MultiMaterial from parsed MultiMaterial data.
  35290. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35291. * @param scene defines the hosting scene
  35292. * @returns a new MultiMaterial
  35293. */
  35294. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35295. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35296. multiMaterial.id = parsedMultiMaterial.id;
  35297. if (BABYLON.Tags) {
  35298. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35299. }
  35300. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35301. var subMatId = parsedMultiMaterial.materials[matIndex];
  35302. if (subMatId) {
  35303. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35304. }
  35305. else {
  35306. multiMaterial.subMaterials.push(null);
  35307. }
  35308. }
  35309. return multiMaterial;
  35310. };
  35311. /**
  35312. * Creates a material from parsed material data
  35313. * @param parsedMaterial defines parsed material data
  35314. * @param scene defines the hosting scene
  35315. * @param rootUrl defines the root URL to use to load textures
  35316. * @returns a new material
  35317. */
  35318. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35319. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35320. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35321. }
  35322. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35323. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35324. if (!BABYLON.LegacyPBRMaterial) {
  35325. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35326. return;
  35327. }
  35328. }
  35329. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35330. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35331. ;
  35332. };
  35333. // Triangle views
  35334. Material._TriangleFillMode = 0;
  35335. Material._WireFrameFillMode = 1;
  35336. Material._PointFillMode = 2;
  35337. // Draw modes
  35338. Material._PointListDrawMode = 3;
  35339. Material._LineListDrawMode = 4;
  35340. Material._LineLoopDrawMode = 5;
  35341. Material._LineStripDrawMode = 6;
  35342. Material._TriangleStripDrawMode = 7;
  35343. Material._TriangleFanDrawMode = 8;
  35344. /**
  35345. * Stores the clock-wise side orientation
  35346. */
  35347. Material._ClockWiseSideOrientation = 0;
  35348. /**
  35349. * Stores the counter clock-wise side orientation
  35350. */
  35351. Material._CounterClockWiseSideOrientation = 1;
  35352. /**
  35353. * The dirty texture flag value
  35354. */
  35355. Material._TextureDirtyFlag = 1;
  35356. /**
  35357. * The dirty light flag value
  35358. */
  35359. Material._LightDirtyFlag = 2;
  35360. /**
  35361. * The dirty fresnel flag value
  35362. */
  35363. Material._FresnelDirtyFlag = 4;
  35364. /**
  35365. * The dirty attribute flag value
  35366. */
  35367. Material._AttributesDirtyFlag = 8;
  35368. /**
  35369. * The dirty misc flag value
  35370. */
  35371. Material._MiscDirtyFlag = 16;
  35372. __decorate([
  35373. BABYLON.serialize()
  35374. ], Material.prototype, "id", void 0);
  35375. __decorate([
  35376. BABYLON.serialize()
  35377. ], Material.prototype, "name", void 0);
  35378. __decorate([
  35379. BABYLON.serialize()
  35380. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35381. __decorate([
  35382. BABYLON.serialize()
  35383. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35384. __decorate([
  35385. BABYLON.serialize()
  35386. ], Material.prototype, "state", void 0);
  35387. __decorate([
  35388. BABYLON.serialize("alpha")
  35389. ], Material.prototype, "_alpha", void 0);
  35390. __decorate([
  35391. BABYLON.serialize("backFaceCulling")
  35392. ], Material.prototype, "_backFaceCulling", void 0);
  35393. __decorate([
  35394. BABYLON.serialize()
  35395. ], Material.prototype, "sideOrientation", void 0);
  35396. __decorate([
  35397. BABYLON.serialize("alphaMode")
  35398. ], Material.prototype, "_alphaMode", void 0);
  35399. __decorate([
  35400. BABYLON.serialize()
  35401. ], Material.prototype, "_needDepthPrePass", void 0);
  35402. __decorate([
  35403. BABYLON.serialize()
  35404. ], Material.prototype, "disableDepthWrite", void 0);
  35405. __decorate([
  35406. BABYLON.serialize()
  35407. ], Material.prototype, "forceDepthWrite", void 0);
  35408. __decorate([
  35409. BABYLON.serialize()
  35410. ], Material.prototype, "separateCullingPass", void 0);
  35411. __decorate([
  35412. BABYLON.serialize("fogEnabled")
  35413. ], Material.prototype, "_fogEnabled", void 0);
  35414. __decorate([
  35415. BABYLON.serialize()
  35416. ], Material.prototype, "pointSize", void 0);
  35417. __decorate([
  35418. BABYLON.serialize()
  35419. ], Material.prototype, "zOffset", void 0);
  35420. __decorate([
  35421. BABYLON.serialize()
  35422. ], Material.prototype, "wireframe", null);
  35423. __decorate([
  35424. BABYLON.serialize()
  35425. ], Material.prototype, "pointsCloud", null);
  35426. __decorate([
  35427. BABYLON.serialize()
  35428. ], Material.prototype, "fillMode", null);
  35429. return Material;
  35430. }());
  35431. BABYLON.Material = Material;
  35432. })(BABYLON || (BABYLON = {}));
  35433. //# sourceMappingURL=babylon.material.js.map
  35434. var BABYLON;
  35435. (function (BABYLON) {
  35436. var UniformBuffer = /** @class */ (function () {
  35437. /**
  35438. * Uniform buffer objects.
  35439. *
  35440. * Handles blocks of uniform on the GPU.
  35441. *
  35442. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35443. *
  35444. * For more information, please refer to :
  35445. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35446. */
  35447. function UniformBuffer(engine, data, dynamic) {
  35448. this._engine = engine;
  35449. this._noUBO = !engine.supportsUniformBuffers;
  35450. this._dynamic = dynamic;
  35451. this._data = data || [];
  35452. this._uniformLocations = {};
  35453. this._uniformSizes = {};
  35454. this._uniformLocationPointer = 0;
  35455. this._needSync = false;
  35456. if (this._noUBO) {
  35457. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35458. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35459. this.updateFloat = this._updateFloatForEffect;
  35460. this.updateFloat2 = this._updateFloat2ForEffect;
  35461. this.updateFloat3 = this._updateFloat3ForEffect;
  35462. this.updateFloat4 = this._updateFloat4ForEffect;
  35463. this.updateMatrix = this._updateMatrixForEffect;
  35464. this.updateVector3 = this._updateVector3ForEffect;
  35465. this.updateVector4 = this._updateVector4ForEffect;
  35466. this.updateColor3 = this._updateColor3ForEffect;
  35467. this.updateColor4 = this._updateColor4ForEffect;
  35468. }
  35469. else {
  35470. this._engine._uniformBuffers.push(this);
  35471. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35472. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35473. this.updateFloat = this._updateFloatForUniform;
  35474. this.updateFloat2 = this._updateFloat2ForUniform;
  35475. this.updateFloat3 = this._updateFloat3ForUniform;
  35476. this.updateFloat4 = this._updateFloat4ForUniform;
  35477. this.updateMatrix = this._updateMatrixForUniform;
  35478. this.updateVector3 = this._updateVector3ForUniform;
  35479. this.updateVector4 = this._updateVector4ForUniform;
  35480. this.updateColor3 = this._updateColor3ForUniform;
  35481. this.updateColor4 = this._updateColor4ForUniform;
  35482. }
  35483. }
  35484. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35485. // Properties
  35486. /**
  35487. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35488. * or just falling back on setUniformXXX calls.
  35489. */
  35490. get: function () {
  35491. return !this._noUBO;
  35492. },
  35493. enumerable: true,
  35494. configurable: true
  35495. });
  35496. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35497. /**
  35498. * Indicates if the WebGL underlying uniform buffer is in sync
  35499. * with the javascript cache data.
  35500. */
  35501. get: function () {
  35502. return !this._needSync;
  35503. },
  35504. enumerable: true,
  35505. configurable: true
  35506. });
  35507. /**
  35508. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35509. * Also, a dynamic UniformBuffer will disable cache verification and always
  35510. * update the underlying WebGL uniform buffer to the GPU.
  35511. */
  35512. UniformBuffer.prototype.isDynamic = function () {
  35513. return this._dynamic !== undefined;
  35514. };
  35515. /**
  35516. * The data cache on JS side.
  35517. */
  35518. UniformBuffer.prototype.getData = function () {
  35519. return this._bufferData;
  35520. };
  35521. /**
  35522. * The underlying WebGL Uniform buffer.
  35523. */
  35524. UniformBuffer.prototype.getBuffer = function () {
  35525. return this._buffer;
  35526. };
  35527. /**
  35528. * std140 layout specifies how to align data within an UBO structure.
  35529. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35530. * for specs.
  35531. */
  35532. UniformBuffer.prototype._fillAlignment = function (size) {
  35533. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35534. // and 4x4 matrices
  35535. // TODO : change if other types are used
  35536. var alignment;
  35537. if (size <= 2) {
  35538. alignment = size;
  35539. }
  35540. else {
  35541. alignment = 4;
  35542. }
  35543. if ((this._uniformLocationPointer % alignment) !== 0) {
  35544. var oldPointer = this._uniformLocationPointer;
  35545. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35546. var diff = this._uniformLocationPointer - oldPointer;
  35547. for (var i = 0; i < diff; i++) {
  35548. this._data.push(0);
  35549. }
  35550. }
  35551. };
  35552. /**
  35553. * Adds an uniform in the buffer.
  35554. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35555. * for the layout to be correct !
  35556. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35557. * @param {number|number[]} size Data size, or data directly.
  35558. */
  35559. UniformBuffer.prototype.addUniform = function (name, size) {
  35560. if (this._noUBO) {
  35561. return;
  35562. }
  35563. if (this._uniformLocations[name] !== undefined) {
  35564. // Already existing uniform
  35565. return;
  35566. }
  35567. // This function must be called in the order of the shader layout !
  35568. // size can be the size of the uniform, or data directly
  35569. var data;
  35570. if (size instanceof Array) {
  35571. data = size;
  35572. size = data.length;
  35573. }
  35574. else {
  35575. size = size;
  35576. data = [];
  35577. // Fill with zeros
  35578. for (var i = 0; i < size; i++) {
  35579. data.push(0);
  35580. }
  35581. }
  35582. this._fillAlignment(size);
  35583. this._uniformSizes[name] = size;
  35584. this._uniformLocations[name] = this._uniformLocationPointer;
  35585. this._uniformLocationPointer += size;
  35586. for (var i = 0; i < size; i++) {
  35587. this._data.push(data[i]);
  35588. }
  35589. this._needSync = true;
  35590. };
  35591. /**
  35592. * Wrapper for addUniform.
  35593. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35594. * @param {Matrix} mat A 4x4 matrix.
  35595. */
  35596. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35597. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35598. };
  35599. /**
  35600. * Wrapper for addUniform.
  35601. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35602. * @param {number} x
  35603. * @param {number} y
  35604. */
  35605. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35606. var temp = [x, y];
  35607. this.addUniform(name, temp);
  35608. };
  35609. /**
  35610. * Wrapper for addUniform.
  35611. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35612. * @param {number} x
  35613. * @param {number} y
  35614. * @param {number} z
  35615. */
  35616. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35617. var temp = [x, y, z];
  35618. this.addUniform(name, temp);
  35619. };
  35620. /**
  35621. * Wrapper for addUniform.
  35622. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35623. * @param {Color3} color
  35624. */
  35625. UniformBuffer.prototype.addColor3 = function (name, color) {
  35626. var temp = new Array();
  35627. color.toArray(temp);
  35628. this.addUniform(name, temp);
  35629. };
  35630. /**
  35631. * Wrapper for addUniform.
  35632. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35633. * @param {Color3} color
  35634. * @param {number} alpha
  35635. */
  35636. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35637. var temp = new Array();
  35638. color.toArray(temp);
  35639. temp.push(alpha);
  35640. this.addUniform(name, temp);
  35641. };
  35642. /**
  35643. * Wrapper for addUniform.
  35644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35645. * @param {Vector3} vector
  35646. */
  35647. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35648. var temp = new Array();
  35649. vector.toArray(temp);
  35650. this.addUniform(name, temp);
  35651. };
  35652. /**
  35653. * Wrapper for addUniform.
  35654. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35655. */
  35656. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35657. this.addUniform(name, 12);
  35658. };
  35659. /**
  35660. * Wrapper for addUniform.
  35661. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35662. */
  35663. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35664. this.addUniform(name, 8);
  35665. };
  35666. /**
  35667. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35668. */
  35669. UniformBuffer.prototype.create = function () {
  35670. if (this._noUBO) {
  35671. return;
  35672. }
  35673. if (this._buffer) {
  35674. return; // nothing to do
  35675. }
  35676. // See spec, alignment must be filled as a vec4
  35677. this._fillAlignment(4);
  35678. this._bufferData = new Float32Array(this._data);
  35679. this._rebuild();
  35680. this._needSync = true;
  35681. };
  35682. UniformBuffer.prototype._rebuild = function () {
  35683. if (this._noUBO) {
  35684. return;
  35685. }
  35686. if (this._dynamic) {
  35687. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35688. }
  35689. else {
  35690. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35691. }
  35692. };
  35693. /**
  35694. * Updates the WebGL Uniform Buffer on the GPU.
  35695. * If the `dynamic` flag is set to true, no cache comparison is done.
  35696. * Otherwise, the buffer will be updated only if the cache differs.
  35697. */
  35698. UniformBuffer.prototype.update = function () {
  35699. if (!this._buffer) {
  35700. this.create();
  35701. return;
  35702. }
  35703. if (!this._dynamic && !this._needSync) {
  35704. return;
  35705. }
  35706. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35707. this._needSync = false;
  35708. };
  35709. /**
  35710. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35711. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35712. * @param {number[]|Float32Array} data Flattened data
  35713. * @param {number} size Size of the data.
  35714. */
  35715. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35716. var location = this._uniformLocations[uniformName];
  35717. if (location === undefined) {
  35718. if (this._buffer) {
  35719. // Cannot add an uniform if the buffer is already created
  35720. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35721. return;
  35722. }
  35723. this.addUniform(uniformName, size);
  35724. location = this._uniformLocations[uniformName];
  35725. }
  35726. if (!this._buffer) {
  35727. this.create();
  35728. }
  35729. if (!this._dynamic) {
  35730. // Cache for static uniform buffers
  35731. var changed = false;
  35732. for (var i = 0; i < size; i++) {
  35733. if (this._bufferData[location + i] !== data[i]) {
  35734. changed = true;
  35735. this._bufferData[location + i] = data[i];
  35736. }
  35737. }
  35738. this._needSync = this._needSync || changed;
  35739. }
  35740. else {
  35741. // No cache for dynamic
  35742. for (var i = 0; i < size; i++) {
  35743. this._bufferData[location + i] = data[i];
  35744. }
  35745. }
  35746. };
  35747. // Update methods
  35748. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35749. // To match std140, matrix must be realigned
  35750. for (var i = 0; i < 3; i++) {
  35751. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35752. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35753. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35754. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35755. }
  35756. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35757. };
  35758. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35759. this._currentEffect.setMatrix3x3(name, matrix);
  35760. };
  35761. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35762. this._currentEffect.setMatrix2x2(name, matrix);
  35763. };
  35764. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35765. // To match std140, matrix must be realigned
  35766. for (var i = 0; i < 2; i++) {
  35767. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35768. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35769. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35770. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35771. }
  35772. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35773. };
  35774. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35775. this._currentEffect.setFloat(name, x);
  35776. };
  35777. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35778. UniformBuffer._tempBuffer[0] = x;
  35779. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35780. };
  35781. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35782. if (suffix === void 0) { suffix = ""; }
  35783. this._currentEffect.setFloat2(name + suffix, x, y);
  35784. };
  35785. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35786. if (suffix === void 0) { suffix = ""; }
  35787. UniformBuffer._tempBuffer[0] = x;
  35788. UniformBuffer._tempBuffer[1] = y;
  35789. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35790. };
  35791. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35792. if (suffix === void 0) { suffix = ""; }
  35793. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35794. };
  35795. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35796. if (suffix === void 0) { suffix = ""; }
  35797. UniformBuffer._tempBuffer[0] = x;
  35798. UniformBuffer._tempBuffer[1] = y;
  35799. UniformBuffer._tempBuffer[2] = z;
  35800. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35801. };
  35802. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35803. if (suffix === void 0) { suffix = ""; }
  35804. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35805. };
  35806. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35807. if (suffix === void 0) { suffix = ""; }
  35808. UniformBuffer._tempBuffer[0] = x;
  35809. UniformBuffer._tempBuffer[1] = y;
  35810. UniformBuffer._tempBuffer[2] = z;
  35811. UniformBuffer._tempBuffer[3] = w;
  35812. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35813. };
  35814. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35815. this._currentEffect.setMatrix(name, mat);
  35816. };
  35817. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35818. this.updateUniform(name, mat.toArray(), 16);
  35819. };
  35820. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35821. this._currentEffect.setVector3(name, vector);
  35822. };
  35823. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35824. vector.toArray(UniformBuffer._tempBuffer);
  35825. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35826. };
  35827. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35828. this._currentEffect.setVector4(name, vector);
  35829. };
  35830. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35831. vector.toArray(UniformBuffer._tempBuffer);
  35832. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35833. };
  35834. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35835. if (suffix === void 0) { suffix = ""; }
  35836. this._currentEffect.setColor3(name + suffix, color);
  35837. };
  35838. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35839. if (suffix === void 0) { suffix = ""; }
  35840. color.toArray(UniformBuffer._tempBuffer);
  35841. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35842. };
  35843. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35844. if (suffix === void 0) { suffix = ""; }
  35845. this._currentEffect.setColor4(name + suffix, color, alpha);
  35846. };
  35847. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35848. if (suffix === void 0) { suffix = ""; }
  35849. color.toArray(UniformBuffer._tempBuffer);
  35850. UniformBuffer._tempBuffer[3] = alpha;
  35851. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35852. };
  35853. /**
  35854. * Sets a sampler uniform on the effect.
  35855. * @param {string} name Name of the sampler.
  35856. * @param {Texture} texture
  35857. */
  35858. UniformBuffer.prototype.setTexture = function (name, texture) {
  35859. this._currentEffect.setTexture(name, texture);
  35860. };
  35861. /**
  35862. * Directly updates the value of the uniform in the cache AND on the GPU.
  35863. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35864. * @param {number[]|Float32Array} data Flattened data
  35865. */
  35866. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35867. this.updateUniform(uniformName, data, data.length);
  35868. this.update();
  35869. };
  35870. /**
  35871. * Binds this uniform buffer to an effect.
  35872. * @param {Effect} effect
  35873. * @param {string} name Name of the uniform block in the shader.
  35874. */
  35875. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35876. this._currentEffect = effect;
  35877. if (this._noUBO || !this._buffer) {
  35878. return;
  35879. }
  35880. effect.bindUniformBuffer(this._buffer, name);
  35881. };
  35882. /**
  35883. * Disposes the uniform buffer.
  35884. */
  35885. UniformBuffer.prototype.dispose = function () {
  35886. if (this._noUBO) {
  35887. return;
  35888. }
  35889. var index = this._engine._uniformBuffers.indexOf(this);
  35890. if (index !== -1) {
  35891. this._engine._uniformBuffers.splice(index, 1);
  35892. }
  35893. if (!this._buffer) {
  35894. return;
  35895. }
  35896. if (this._engine._releaseBuffer(this._buffer)) {
  35897. this._buffer = null;
  35898. }
  35899. };
  35900. // Pool for avoiding memory leaks
  35901. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35902. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35903. return UniformBuffer;
  35904. }());
  35905. BABYLON.UniformBuffer = UniformBuffer;
  35906. })(BABYLON || (BABYLON = {}));
  35907. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35908. var BABYLON;
  35909. (function (BABYLON) {
  35910. /**
  35911. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35912. */
  35913. var VertexData = /** @class */ (function () {
  35914. function VertexData() {
  35915. }
  35916. /**
  35917. * Uses the passed data array to set the set the values for the specified kind of data
  35918. * @param data a linear array of floating numbers
  35919. * @param kind the type of data that is being set, eg positions, colors etc
  35920. */
  35921. VertexData.prototype.set = function (data, kind) {
  35922. switch (kind) {
  35923. case BABYLON.VertexBuffer.PositionKind:
  35924. this.positions = data;
  35925. break;
  35926. case BABYLON.VertexBuffer.NormalKind:
  35927. this.normals = data;
  35928. break;
  35929. case BABYLON.VertexBuffer.TangentKind:
  35930. this.tangents = data;
  35931. break;
  35932. case BABYLON.VertexBuffer.UVKind:
  35933. this.uvs = data;
  35934. break;
  35935. case BABYLON.VertexBuffer.UV2Kind:
  35936. this.uvs2 = data;
  35937. break;
  35938. case BABYLON.VertexBuffer.UV3Kind:
  35939. this.uvs3 = data;
  35940. break;
  35941. case BABYLON.VertexBuffer.UV4Kind:
  35942. this.uvs4 = data;
  35943. break;
  35944. case BABYLON.VertexBuffer.UV5Kind:
  35945. this.uvs5 = data;
  35946. break;
  35947. case BABYLON.VertexBuffer.UV6Kind:
  35948. this.uvs6 = data;
  35949. break;
  35950. case BABYLON.VertexBuffer.ColorKind:
  35951. this.colors = data;
  35952. break;
  35953. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35954. this.matricesIndices = data;
  35955. break;
  35956. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35957. this.matricesWeights = data;
  35958. break;
  35959. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35960. this.matricesIndicesExtra = data;
  35961. break;
  35962. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35963. this.matricesWeightsExtra = data;
  35964. break;
  35965. }
  35966. };
  35967. /**
  35968. * Associates the vertexData to the passed Mesh.
  35969. * Sets it as updatable or not (default `false`)
  35970. * @param mesh the mesh the vertexData is applied to
  35971. * @param updatable when used and having the value true allows new data to update the vertexData
  35972. * @returns the VertexData
  35973. */
  35974. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35975. this._applyTo(mesh, updatable);
  35976. return this;
  35977. };
  35978. /**
  35979. * Associates the vertexData to the passed Geometry.
  35980. * Sets it as updatable or not (default `false`)
  35981. * @param geometry the geometry the vertexData is applied to
  35982. * @param updatable when used and having the value true allows new data to update the vertexData
  35983. * @returns VertexData
  35984. */
  35985. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35986. this._applyTo(geometry, updatable);
  35987. return this;
  35988. };
  35989. /**
  35990. * Updates the associated mesh
  35991. * @param mesh the mesh to be updated
  35992. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35993. * @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
  35994. * @returns VertexData
  35995. */
  35996. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35997. this._update(mesh);
  35998. return this;
  35999. };
  36000. /**
  36001. * Updates the associated geometry
  36002. * @param geometry the geometry to be updated
  36003. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36004. * @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
  36005. * @returns VertexData.
  36006. */
  36007. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36008. this._update(geometry);
  36009. return this;
  36010. };
  36011. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36012. if (updatable === void 0) { updatable = false; }
  36013. if (this.positions) {
  36014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36015. }
  36016. if (this.normals) {
  36017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36018. }
  36019. if (this.tangents) {
  36020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36021. }
  36022. if (this.uvs) {
  36023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36024. }
  36025. if (this.uvs2) {
  36026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36027. }
  36028. if (this.uvs3) {
  36029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36030. }
  36031. if (this.uvs4) {
  36032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36033. }
  36034. if (this.uvs5) {
  36035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36036. }
  36037. if (this.uvs6) {
  36038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36039. }
  36040. if (this.colors) {
  36041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36042. }
  36043. if (this.matricesIndices) {
  36044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36045. }
  36046. if (this.matricesWeights) {
  36047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36048. }
  36049. if (this.matricesIndicesExtra) {
  36050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36051. }
  36052. if (this.matricesWeightsExtra) {
  36053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36054. }
  36055. if (this.indices) {
  36056. meshOrGeometry.setIndices(this.indices, null, updatable);
  36057. }
  36058. return this;
  36059. };
  36060. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36061. if (this.positions) {
  36062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36063. }
  36064. if (this.normals) {
  36065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36066. }
  36067. if (this.tangents) {
  36068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36069. }
  36070. if (this.uvs) {
  36071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36072. }
  36073. if (this.uvs2) {
  36074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36075. }
  36076. if (this.uvs3) {
  36077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36078. }
  36079. if (this.uvs4) {
  36080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36081. }
  36082. if (this.uvs5) {
  36083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36084. }
  36085. if (this.uvs6) {
  36086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36087. }
  36088. if (this.colors) {
  36089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36090. }
  36091. if (this.matricesIndices) {
  36092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36093. }
  36094. if (this.matricesWeights) {
  36095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36096. }
  36097. if (this.matricesIndicesExtra) {
  36098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36099. }
  36100. if (this.matricesWeightsExtra) {
  36101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36102. }
  36103. if (this.indices) {
  36104. meshOrGeometry.setIndices(this.indices, null);
  36105. }
  36106. return this;
  36107. };
  36108. /**
  36109. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36110. * @param matrix the transforming matrix
  36111. * @returns the VertexData
  36112. */
  36113. VertexData.prototype.transform = function (matrix) {
  36114. var transformed = BABYLON.Vector3.Zero();
  36115. var index;
  36116. if (this.positions) {
  36117. var position = BABYLON.Vector3.Zero();
  36118. for (index = 0; index < this.positions.length; index += 3) {
  36119. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36120. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36121. this.positions[index] = transformed.x;
  36122. this.positions[index + 1] = transformed.y;
  36123. this.positions[index + 2] = transformed.z;
  36124. }
  36125. }
  36126. if (this.normals) {
  36127. var normal = BABYLON.Vector3.Zero();
  36128. for (index = 0; index < this.normals.length; index += 3) {
  36129. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36130. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36131. this.normals[index] = transformed.x;
  36132. this.normals[index + 1] = transformed.y;
  36133. this.normals[index + 2] = transformed.z;
  36134. }
  36135. }
  36136. if (this.tangents) {
  36137. var tangent = BABYLON.Vector4.Zero();
  36138. var tangentTransformed = BABYLON.Vector4.Zero();
  36139. for (index = 0; index < this.tangents.length; index += 4) {
  36140. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36141. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36142. this.tangents[index] = tangentTransformed.x;
  36143. this.tangents[index + 1] = tangentTransformed.y;
  36144. this.tangents[index + 2] = tangentTransformed.z;
  36145. this.tangents[index + 3] = tangentTransformed.w;
  36146. }
  36147. }
  36148. return this;
  36149. };
  36150. /**
  36151. * Merges the passed VertexData into the current one
  36152. * @param other the VertexData to be merged into the current one
  36153. * @returns the modified VertexData
  36154. */
  36155. VertexData.prototype.merge = function (other) {
  36156. this._validate();
  36157. other._validate();
  36158. if (!this.normals !== !other.normals ||
  36159. !this.tangents !== !other.tangents ||
  36160. !this.uvs !== !other.uvs ||
  36161. !this.uvs2 !== !other.uvs2 ||
  36162. !this.uvs3 !== !other.uvs3 ||
  36163. !this.uvs4 !== !other.uvs4 ||
  36164. !this.uvs5 !== !other.uvs5 ||
  36165. !this.uvs6 !== !other.uvs6 ||
  36166. !this.colors !== !other.colors ||
  36167. !this.matricesIndices !== !other.matricesIndices ||
  36168. !this.matricesWeights !== !other.matricesWeights ||
  36169. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36170. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36171. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36172. }
  36173. if (other.indices) {
  36174. if (!this.indices) {
  36175. this.indices = [];
  36176. }
  36177. var offset = this.positions ? this.positions.length / 3 : 0;
  36178. for (var index = 0; index < other.indices.length; index++) {
  36179. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36180. this.indices.push(other.indices[index] + offset);
  36181. }
  36182. }
  36183. this.positions = this._mergeElement(this.positions, other.positions);
  36184. this.normals = this._mergeElement(this.normals, other.normals);
  36185. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36186. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36187. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36188. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36189. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36190. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36191. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36192. this.colors = this._mergeElement(this.colors, other.colors);
  36193. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36194. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36195. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36196. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36197. return this;
  36198. };
  36199. VertexData.prototype._mergeElement = function (source, other) {
  36200. if (!source) {
  36201. return other;
  36202. }
  36203. if (!other) {
  36204. return source;
  36205. }
  36206. var len = other.length + source.length;
  36207. var isSrcTypedArray = source instanceof Float32Array;
  36208. var isOthTypedArray = other instanceof Float32Array;
  36209. // use non-loop method when the source is Float32Array
  36210. if (isSrcTypedArray) {
  36211. var ret32 = new Float32Array(len);
  36212. ret32.set(source);
  36213. ret32.set(other, source.length);
  36214. return ret32;
  36215. // source is number[], when other is also use concat
  36216. }
  36217. else if (!isOthTypedArray) {
  36218. return source.concat(other);
  36219. // source is a number[], but other is a Float32Array, loop required
  36220. }
  36221. else {
  36222. var ret = source.slice(0); // copy source to a separate array
  36223. for (var i = 0, len = other.length; i < len; i++) {
  36224. ret.push(other[i]);
  36225. }
  36226. return ret;
  36227. }
  36228. };
  36229. VertexData.prototype._validate = function () {
  36230. if (!this.positions) {
  36231. throw new Error("Positions are required");
  36232. }
  36233. var getElementCount = function (kind, values) {
  36234. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36235. if ((values.length % stride) !== 0) {
  36236. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36237. }
  36238. return values.length / stride;
  36239. };
  36240. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36241. var validateElementCount = function (kind, values) {
  36242. var elementCount = getElementCount(kind, values);
  36243. if (elementCount !== positionsElementCount) {
  36244. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36245. }
  36246. };
  36247. if (this.normals)
  36248. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36249. if (this.tangents)
  36250. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36251. if (this.uvs)
  36252. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36253. if (this.uvs2)
  36254. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36255. if (this.uvs3)
  36256. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36257. if (this.uvs4)
  36258. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36259. if (this.uvs5)
  36260. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36261. if (this.uvs6)
  36262. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36263. if (this.colors)
  36264. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36265. if (this.matricesIndices)
  36266. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36267. if (this.matricesWeights)
  36268. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36269. if (this.matricesIndicesExtra)
  36270. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36271. if (this.matricesWeightsExtra)
  36272. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36273. };
  36274. /**
  36275. * Serializes the VertexData
  36276. * @returns a serialized object
  36277. */
  36278. VertexData.prototype.serialize = function () {
  36279. var serializationObject = this.serialize();
  36280. if (this.positions) {
  36281. serializationObject.positions = this.positions;
  36282. }
  36283. if (this.normals) {
  36284. serializationObject.normals = this.normals;
  36285. }
  36286. if (this.tangents) {
  36287. serializationObject.tangents = this.tangents;
  36288. }
  36289. if (this.uvs) {
  36290. serializationObject.uvs = this.uvs;
  36291. }
  36292. if (this.uvs2) {
  36293. serializationObject.uvs2 = this.uvs2;
  36294. }
  36295. if (this.uvs3) {
  36296. serializationObject.uvs3 = this.uvs3;
  36297. }
  36298. if (this.uvs4) {
  36299. serializationObject.uvs4 = this.uvs4;
  36300. }
  36301. if (this.uvs5) {
  36302. serializationObject.uvs5 = this.uvs5;
  36303. }
  36304. if (this.uvs6) {
  36305. serializationObject.uvs6 = this.uvs6;
  36306. }
  36307. if (this.colors) {
  36308. serializationObject.colors = this.colors;
  36309. }
  36310. if (this.matricesIndices) {
  36311. serializationObject.matricesIndices = this.matricesIndices;
  36312. serializationObject.matricesIndices._isExpanded = true;
  36313. }
  36314. if (this.matricesWeights) {
  36315. serializationObject.matricesWeights = this.matricesWeights;
  36316. }
  36317. if (this.matricesIndicesExtra) {
  36318. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36319. serializationObject.matricesIndicesExtra._isExpanded = true;
  36320. }
  36321. if (this.matricesWeightsExtra) {
  36322. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36323. }
  36324. serializationObject.indices = this.indices;
  36325. return serializationObject;
  36326. };
  36327. // Statics
  36328. /**
  36329. * Extracts the vertexData from a mesh
  36330. * @param mesh the mesh from which to extract the VertexData
  36331. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36332. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36333. * @returns the object VertexData associated to the passed mesh
  36334. */
  36335. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36336. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36337. };
  36338. /**
  36339. * Extracts the vertexData from the geometry
  36340. * @param geometry the geometry from which to extract the VertexData
  36341. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36342. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36343. * @returns the object VertexData associated to the passed mesh
  36344. */
  36345. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36346. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36347. };
  36348. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36349. var result = new VertexData();
  36350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36351. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36352. }
  36353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36354. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36355. }
  36356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36357. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36358. }
  36359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36360. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36361. }
  36362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36363. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36364. }
  36365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36366. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36367. }
  36368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36369. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36370. }
  36371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36372. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36373. }
  36374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36375. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36376. }
  36377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36378. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36379. }
  36380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36381. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36382. }
  36383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36384. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36385. }
  36386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36387. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36388. }
  36389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36390. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36391. }
  36392. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36393. return result;
  36394. };
  36395. /**
  36396. * Creates the VertexData for a Ribbon
  36397. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36398. * * pathArray array of paths, each of which an array of successive Vector3
  36399. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36400. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36401. * * 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
  36402. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36403. * * 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)
  36404. * * 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)
  36405. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36406. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36407. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36408. * @returns the VertexData of the ribbon
  36409. */
  36410. VertexData.CreateRibbon = function (options) {
  36411. var pathArray = options.pathArray;
  36412. var closeArray = options.closeArray || false;
  36413. var closePath = options.closePath || false;
  36414. var invertUV = options.invertUV || false;
  36415. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36416. var offset = options.offset || defaultOffset;
  36417. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36418. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36419. var customUV = options.uvs;
  36420. var customColors = options.colors;
  36421. var positions = [];
  36422. var indices = [];
  36423. var normals = [];
  36424. var uvs = [];
  36425. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36426. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36427. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36428. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36429. var minlg; // minimal length among all paths from pathArray
  36430. var lg = []; // array of path lengths : nb of vertex per path
  36431. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36432. var p; // path iterator
  36433. var i; // point iterator
  36434. var j; // point iterator
  36435. // if single path in pathArray
  36436. if (pathArray.length < 2) {
  36437. var ar1 = [];
  36438. var ar2 = [];
  36439. for (i = 0; i < pathArray[0].length - offset; i++) {
  36440. ar1.push(pathArray[0][i]);
  36441. ar2.push(pathArray[0][i + offset]);
  36442. }
  36443. pathArray = [ar1, ar2];
  36444. }
  36445. // positions and horizontal distances (u)
  36446. var idc = 0;
  36447. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36448. var path;
  36449. var l;
  36450. minlg = pathArray[0].length;
  36451. var vectlg;
  36452. var dist;
  36453. for (p = 0; p < pathArray.length; p++) {
  36454. uTotalDistance[p] = 0;
  36455. us[p] = [0];
  36456. path = pathArray[p];
  36457. l = path.length;
  36458. minlg = (minlg < l) ? minlg : l;
  36459. j = 0;
  36460. while (j < l) {
  36461. positions.push(path[j].x, path[j].y, path[j].z);
  36462. if (j > 0) {
  36463. vectlg = path[j].subtract(path[j - 1]).length();
  36464. dist = vectlg + uTotalDistance[p];
  36465. us[p].push(dist);
  36466. uTotalDistance[p] = dist;
  36467. }
  36468. j++;
  36469. }
  36470. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36471. j--;
  36472. positions.push(path[0].x, path[0].y, path[0].z);
  36473. vectlg = path[j].subtract(path[0]).length();
  36474. dist = vectlg + uTotalDistance[p];
  36475. us[p].push(dist);
  36476. uTotalDistance[p] = dist;
  36477. }
  36478. lg[p] = l + closePathCorr;
  36479. idx[p] = idc;
  36480. idc += (l + closePathCorr);
  36481. }
  36482. // vertical distances (v)
  36483. var path1;
  36484. var path2;
  36485. var vertex1 = null;
  36486. var vertex2 = null;
  36487. for (i = 0; i < minlg + closePathCorr; i++) {
  36488. vTotalDistance[i] = 0;
  36489. vs[i] = [0];
  36490. for (p = 0; p < pathArray.length - 1; p++) {
  36491. path1 = pathArray[p];
  36492. path2 = pathArray[p + 1];
  36493. if (i === minlg) { // closePath
  36494. vertex1 = path1[0];
  36495. vertex2 = path2[0];
  36496. }
  36497. else {
  36498. vertex1 = path1[i];
  36499. vertex2 = path2[i];
  36500. }
  36501. vectlg = vertex2.subtract(vertex1).length();
  36502. dist = vectlg + vTotalDistance[i];
  36503. vs[i].push(dist);
  36504. vTotalDistance[i] = dist;
  36505. }
  36506. if (closeArray && vertex2 && vertex1) {
  36507. path1 = pathArray[p];
  36508. path2 = pathArray[0];
  36509. if (i === minlg) { // closePath
  36510. vertex2 = path2[0];
  36511. }
  36512. vectlg = vertex2.subtract(vertex1).length();
  36513. dist = vectlg + vTotalDistance[i];
  36514. vTotalDistance[i] = dist;
  36515. }
  36516. }
  36517. // uvs
  36518. var u;
  36519. var v;
  36520. if (customUV) {
  36521. for (p = 0; p < customUV.length; p++) {
  36522. uvs.push(customUV[p].x, customUV[p].y);
  36523. }
  36524. }
  36525. else {
  36526. for (p = 0; p < pathArray.length; p++) {
  36527. for (i = 0; i < minlg + closePathCorr; i++) {
  36528. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36529. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36530. if (invertUV) {
  36531. uvs.push(v, u);
  36532. }
  36533. else {
  36534. uvs.push(u, v);
  36535. }
  36536. }
  36537. }
  36538. }
  36539. // indices
  36540. p = 0; // path index
  36541. var pi = 0; // positions array index
  36542. var l1 = lg[p] - 1; // path1 length
  36543. var l2 = lg[p + 1] - 1; // path2 length
  36544. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36545. var shft = idx[1] - idx[0]; // shift
  36546. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36547. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36548. // 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
  36549. indices.push(pi, pi + shft, pi + 1);
  36550. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36551. pi += 1;
  36552. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36553. p++;
  36554. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36555. shft = idx[0] - idx[p];
  36556. l1 = lg[p] - 1;
  36557. l2 = lg[0] - 1;
  36558. }
  36559. else {
  36560. shft = idx[p + 1] - idx[p];
  36561. l1 = lg[p] - 1;
  36562. l2 = lg[p + 1] - 1;
  36563. }
  36564. pi = idx[p];
  36565. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36566. }
  36567. }
  36568. // normals
  36569. VertexData.ComputeNormals(positions, indices, normals);
  36570. if (closePath) { // update both the first and last vertex normals to their average value
  36571. var indexFirst = 0;
  36572. var indexLast = 0;
  36573. for (p = 0; p < pathArray.length; p++) {
  36574. indexFirst = idx[p] * 3;
  36575. if (p + 1 < pathArray.length) {
  36576. indexLast = (idx[p + 1] - 1) * 3;
  36577. }
  36578. else {
  36579. indexLast = normals.length - 3;
  36580. }
  36581. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36582. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36583. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36584. normals[indexLast] = normals[indexFirst];
  36585. normals[indexLast + 1] = normals[indexFirst + 1];
  36586. normals[indexLast + 2] = normals[indexFirst + 2];
  36587. }
  36588. }
  36589. // sides
  36590. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36591. // Colors
  36592. var colors = null;
  36593. if (customColors) {
  36594. colors = new Float32Array(customColors.length * 4);
  36595. for (var c = 0; c < customColors.length; c++) {
  36596. colors[c * 4] = customColors[c].r;
  36597. colors[c * 4 + 1] = customColors[c].g;
  36598. colors[c * 4 + 2] = customColors[c].b;
  36599. colors[c * 4 + 3] = customColors[c].a;
  36600. }
  36601. }
  36602. // Result
  36603. var vertexData = new VertexData();
  36604. var positions32 = new Float32Array(positions);
  36605. var normals32 = new Float32Array(normals);
  36606. var uvs32 = new Float32Array(uvs);
  36607. vertexData.indices = indices;
  36608. vertexData.positions = positions32;
  36609. vertexData.normals = normals32;
  36610. vertexData.uvs = uvs32;
  36611. if (colors) {
  36612. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36613. }
  36614. if (closePath) {
  36615. vertexData._idx = idx;
  36616. }
  36617. return vertexData;
  36618. };
  36619. /**
  36620. * Creates the VertexData for a box
  36621. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36622. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36623. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36624. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36625. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36626. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36627. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36628. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36629. * * 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)
  36630. * * 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)
  36631. * @returns the VertexData of the box
  36632. */
  36633. VertexData.CreateBox = function (options) {
  36634. var normalsSource = [
  36635. new BABYLON.Vector3(0, 0, 1),
  36636. new BABYLON.Vector3(0, 0, -1),
  36637. new BABYLON.Vector3(1, 0, 0),
  36638. new BABYLON.Vector3(-1, 0, 0),
  36639. new BABYLON.Vector3(0, 1, 0),
  36640. new BABYLON.Vector3(0, -1, 0)
  36641. ];
  36642. var indices = [];
  36643. var positions = [];
  36644. var normals = [];
  36645. var uvs = [];
  36646. var width = options.width || options.size || 1;
  36647. var height = options.height || options.size || 1;
  36648. var depth = options.depth || options.size || 1;
  36649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36650. var faceUV = options.faceUV || new Array(6);
  36651. var faceColors = options.faceColors;
  36652. var colors = [];
  36653. // default face colors and UV if undefined
  36654. for (var f = 0; f < 6; f++) {
  36655. if (faceUV[f] === undefined) {
  36656. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36657. }
  36658. if (faceColors && faceColors[f] === undefined) {
  36659. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36660. }
  36661. }
  36662. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36663. // Create each face in turn.
  36664. for (var index = 0; index < normalsSource.length; index++) {
  36665. var normal = normalsSource[index];
  36666. // Get two vectors perpendicular to the face normal and to each other.
  36667. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36668. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36669. // Six indices (two triangles) per face.
  36670. var verticesLength = positions.length / 3;
  36671. indices.push(verticesLength);
  36672. indices.push(verticesLength + 1);
  36673. indices.push(verticesLength + 2);
  36674. indices.push(verticesLength);
  36675. indices.push(verticesLength + 2);
  36676. indices.push(verticesLength + 3);
  36677. // Four vertices per face.
  36678. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36679. positions.push(vertex.x, vertex.y, vertex.z);
  36680. normals.push(normal.x, normal.y, normal.z);
  36681. uvs.push(faceUV[index].z, faceUV[index].w);
  36682. if (faceColors) {
  36683. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36684. }
  36685. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36686. positions.push(vertex.x, vertex.y, vertex.z);
  36687. normals.push(normal.x, normal.y, normal.z);
  36688. uvs.push(faceUV[index].x, faceUV[index].w);
  36689. if (faceColors) {
  36690. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36691. }
  36692. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36693. positions.push(vertex.x, vertex.y, vertex.z);
  36694. normals.push(normal.x, normal.y, normal.z);
  36695. uvs.push(faceUV[index].x, faceUV[index].y);
  36696. if (faceColors) {
  36697. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36698. }
  36699. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36700. positions.push(vertex.x, vertex.y, vertex.z);
  36701. normals.push(normal.x, normal.y, normal.z);
  36702. uvs.push(faceUV[index].z, faceUV[index].y);
  36703. if (faceColors) {
  36704. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36705. }
  36706. }
  36707. // sides
  36708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36709. // Result
  36710. var vertexData = new VertexData();
  36711. vertexData.indices = indices;
  36712. vertexData.positions = positions;
  36713. vertexData.normals = normals;
  36714. vertexData.uvs = uvs;
  36715. if (faceColors) {
  36716. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36717. vertexData.colors = totalColors;
  36718. }
  36719. return vertexData;
  36720. };
  36721. /**
  36722. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36723. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36724. * * segments sets the number of horizontal strips optional, default 32
  36725. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36726. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36727. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36728. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36729. * * 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
  36730. * * 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
  36731. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36732. * * 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)
  36733. * * 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)
  36734. * @returns the VertexData of the ellipsoid
  36735. */
  36736. VertexData.CreateSphere = function (options) {
  36737. var segments = options.segments || 32;
  36738. var diameterX = options.diameterX || options.diameter || 1;
  36739. var diameterY = options.diameterY || options.diameter || 1;
  36740. var diameterZ = options.diameterZ || options.diameter || 1;
  36741. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36742. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36743. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36744. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36745. var totalZRotationSteps = 2 + segments;
  36746. var totalYRotationSteps = 2 * totalZRotationSteps;
  36747. var indices = [];
  36748. var positions = [];
  36749. var normals = [];
  36750. var uvs = [];
  36751. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36752. var normalizedZ = zRotationStep / totalZRotationSteps;
  36753. var angleZ = normalizedZ * Math.PI * slice;
  36754. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36755. var normalizedY = yRotationStep / totalYRotationSteps;
  36756. var angleY = normalizedY * Math.PI * 2 * arc;
  36757. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36758. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36759. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36760. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36761. var vertex = complete.multiply(radius);
  36762. var normal = complete.divide(radius).normalize();
  36763. positions.push(vertex.x, vertex.y, vertex.z);
  36764. normals.push(normal.x, normal.y, normal.z);
  36765. uvs.push(normalizedY, normalizedZ);
  36766. }
  36767. if (zRotationStep > 0) {
  36768. var verticesCount = positions.length / 3;
  36769. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36770. indices.push((firstIndex));
  36771. indices.push((firstIndex + 1));
  36772. indices.push(firstIndex + totalYRotationSteps + 1);
  36773. indices.push((firstIndex + totalYRotationSteps + 1));
  36774. indices.push((firstIndex + 1));
  36775. indices.push((firstIndex + totalYRotationSteps + 2));
  36776. }
  36777. }
  36778. }
  36779. // Sides
  36780. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36781. // Result
  36782. var vertexData = new VertexData();
  36783. vertexData.indices = indices;
  36784. vertexData.positions = positions;
  36785. vertexData.normals = normals;
  36786. vertexData.uvs = uvs;
  36787. return vertexData;
  36788. };
  36789. /**
  36790. * Creates the VertexData for a cylinder, cone or prism
  36791. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36792. * * height sets the height (y direction) of the cylinder, optional, default 2
  36793. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36794. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36795. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36796. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36797. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36798. * * 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
  36799. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36800. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36801. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36802. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36803. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36804. * * 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)
  36805. * * 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)
  36806. * @returns the VertexData of the cylinder, cone or prism
  36807. */
  36808. VertexData.CreateCylinder = function (options) {
  36809. var height = options.height || 2;
  36810. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36811. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36812. var tessellation = options.tessellation || 24;
  36813. var subdivisions = options.subdivisions || 1;
  36814. var hasRings = options.hasRings ? true : false;
  36815. var enclose = options.enclose ? true : false;
  36816. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36817. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36818. var faceUV = options.faceUV || new Array(3);
  36819. var faceColors = options.faceColors;
  36820. // default face colors and UV if undefined
  36821. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36822. var ringNb = (hasRings) ? subdivisions : 1;
  36823. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36824. var f;
  36825. for (f = 0; f < surfaceNb; f++) {
  36826. if (faceColors && faceColors[f] === undefined) {
  36827. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36828. }
  36829. }
  36830. for (f = 0; f < surfaceNb; f++) {
  36831. if (faceUV && faceUV[f] === undefined) {
  36832. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36833. }
  36834. }
  36835. var indices = new Array();
  36836. var positions = new Array();
  36837. var normals = new Array();
  36838. var uvs = new Array();
  36839. var colors = new Array();
  36840. var angle_step = Math.PI * 2 * arc / tessellation;
  36841. var angle;
  36842. var h;
  36843. var radius;
  36844. var tan = (diameterBottom - diameterTop) / 2 / height;
  36845. var ringVertex = BABYLON.Vector3.Zero();
  36846. var ringNormal = BABYLON.Vector3.Zero();
  36847. var ringFirstVertex = BABYLON.Vector3.Zero();
  36848. var ringFirstNormal = BABYLON.Vector3.Zero();
  36849. var quadNormal = BABYLON.Vector3.Zero();
  36850. var Y = BABYLON.Axis.Y;
  36851. // positions, normals, uvs
  36852. var i;
  36853. var j;
  36854. var r;
  36855. var ringIdx = 1;
  36856. var s = 1; // surface index
  36857. var cs = 0;
  36858. var v = 0;
  36859. for (i = 0; i <= subdivisions; i++) {
  36860. h = i / subdivisions;
  36861. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36862. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36863. for (r = 0; r < ringIdx; r++) {
  36864. if (hasRings) {
  36865. s += r;
  36866. }
  36867. if (enclose) {
  36868. s += 2 * r;
  36869. }
  36870. for (j = 0; j <= tessellation; j++) {
  36871. angle = j * angle_step;
  36872. // position
  36873. ringVertex.x = Math.cos(-angle) * radius;
  36874. ringVertex.y = -height / 2 + h * height;
  36875. ringVertex.z = Math.sin(-angle) * radius;
  36876. // normal
  36877. if (diameterTop === 0 && i === subdivisions) {
  36878. // if no top cap, reuse former normals
  36879. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36880. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36881. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36882. }
  36883. else {
  36884. ringNormal.x = ringVertex.x;
  36885. ringNormal.z = ringVertex.z;
  36886. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36887. ringNormal.normalize();
  36888. }
  36889. // keep first ring vertex values for enclose
  36890. if (j === 0) {
  36891. ringFirstVertex.copyFrom(ringVertex);
  36892. ringFirstNormal.copyFrom(ringNormal);
  36893. }
  36894. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36895. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36896. if (hasRings) {
  36897. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36898. }
  36899. else {
  36900. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36901. }
  36902. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36903. if (faceColors) {
  36904. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36905. }
  36906. }
  36907. // if enclose, add four vertices and their dedicated normals
  36908. if (arc !== 1 && enclose) {
  36909. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36910. positions.push(0, ringVertex.y, 0);
  36911. positions.push(0, ringVertex.y, 0);
  36912. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36913. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36914. quadNormal.normalize();
  36915. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36916. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36917. quadNormal.normalize();
  36918. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36919. if (hasRings) {
  36920. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36921. }
  36922. else {
  36923. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36924. }
  36925. uvs.push(faceUV[s + 1].x, v);
  36926. uvs.push(faceUV[s + 1].z, v);
  36927. if (hasRings) {
  36928. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36929. }
  36930. else {
  36931. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36932. }
  36933. uvs.push(faceUV[s + 2].x, v);
  36934. uvs.push(faceUV[s + 2].z, v);
  36935. if (faceColors) {
  36936. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36937. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36938. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36939. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36940. }
  36941. }
  36942. if (cs !== s) {
  36943. cs = s;
  36944. }
  36945. }
  36946. }
  36947. // indices
  36948. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36949. var s;
  36950. i = 0;
  36951. for (s = 0; s < subdivisions; s++) {
  36952. var i0 = 0;
  36953. var i1 = 0;
  36954. var i2 = 0;
  36955. var i3 = 0;
  36956. for (j = 0; j < tessellation; j++) {
  36957. i0 = i * (e + 1) + j;
  36958. i1 = (i + 1) * (e + 1) + j;
  36959. i2 = i * (e + 1) + (j + 1);
  36960. i3 = (i + 1) * (e + 1) + (j + 1);
  36961. indices.push(i0, i1, i2);
  36962. indices.push(i3, i2, i1);
  36963. }
  36964. if (arc !== 1 && enclose) { // if enclose, add two quads
  36965. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36966. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36967. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36968. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36969. }
  36970. i = (hasRings) ? (i + 2) : (i + 1);
  36971. }
  36972. // Caps
  36973. var createCylinderCap = function (isTop) {
  36974. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36975. if (radius === 0) {
  36976. return;
  36977. }
  36978. // Cap positions, normals & uvs
  36979. var angle;
  36980. var circleVector;
  36981. var i;
  36982. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36983. var c = null;
  36984. if (faceColors) {
  36985. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36986. }
  36987. // cap center
  36988. var vbase = positions.length / 3;
  36989. var offset = isTop ? height / 2 : -height / 2;
  36990. var center = new BABYLON.Vector3(0, offset, 0);
  36991. positions.push(center.x, center.y, center.z);
  36992. normals.push(0, isTop ? 1 : -1, 0);
  36993. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36994. if (c) {
  36995. colors.push(c.r, c.g, c.b, c.a);
  36996. }
  36997. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36998. for (i = 0; i <= tessellation; i++) {
  36999. angle = Math.PI * 2 * i * arc / tessellation;
  37000. var cos = Math.cos(-angle);
  37001. var sin = Math.sin(-angle);
  37002. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37003. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37004. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37005. normals.push(0, isTop ? 1 : -1, 0);
  37006. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37007. if (c) {
  37008. colors.push(c.r, c.g, c.b, c.a);
  37009. }
  37010. }
  37011. // Cap indices
  37012. for (i = 0; i < tessellation; i++) {
  37013. if (!isTop) {
  37014. indices.push(vbase);
  37015. indices.push(vbase + (i + 1));
  37016. indices.push(vbase + (i + 2));
  37017. }
  37018. else {
  37019. indices.push(vbase);
  37020. indices.push(vbase + (i + 2));
  37021. indices.push(vbase + (i + 1));
  37022. }
  37023. }
  37024. };
  37025. // add caps to geometry
  37026. createCylinderCap(false);
  37027. createCylinderCap(true);
  37028. // Sides
  37029. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37030. var vertexData = new VertexData();
  37031. vertexData.indices = indices;
  37032. vertexData.positions = positions;
  37033. vertexData.normals = normals;
  37034. vertexData.uvs = uvs;
  37035. if (faceColors) {
  37036. vertexData.colors = colors;
  37037. }
  37038. return vertexData;
  37039. };
  37040. /**
  37041. * Creates the VertexData for a torus
  37042. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37043. * * diameter the diameter of the torus, optional default 1
  37044. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37045. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37046. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37047. * * 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)
  37048. * * 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)
  37049. * @returns the VertexData of the torus
  37050. */
  37051. VertexData.CreateTorus = function (options) {
  37052. var indices = [];
  37053. var positions = [];
  37054. var normals = [];
  37055. var uvs = [];
  37056. var diameter = options.diameter || 1;
  37057. var thickness = options.thickness || 0.5;
  37058. var tessellation = options.tessellation || 16;
  37059. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37060. var stride = tessellation + 1;
  37061. for (var i = 0; i <= tessellation; i++) {
  37062. var u = i / tessellation;
  37063. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37064. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37065. for (var j = 0; j <= tessellation; j++) {
  37066. var v = 1 - j / tessellation;
  37067. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37068. var dx = Math.cos(innerAngle);
  37069. var dy = Math.sin(innerAngle);
  37070. // Create a vertex.
  37071. var normal = new BABYLON.Vector3(dx, dy, 0);
  37072. var position = normal.scale(thickness / 2);
  37073. var textureCoordinate = new BABYLON.Vector2(u, v);
  37074. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37075. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37076. positions.push(position.x, position.y, position.z);
  37077. normals.push(normal.x, normal.y, normal.z);
  37078. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37079. // And create indices for two triangles.
  37080. var nextI = (i + 1) % stride;
  37081. var nextJ = (j + 1) % stride;
  37082. indices.push(i * stride + j);
  37083. indices.push(i * stride + nextJ);
  37084. indices.push(nextI * stride + j);
  37085. indices.push(i * stride + nextJ);
  37086. indices.push(nextI * stride + nextJ);
  37087. indices.push(nextI * stride + j);
  37088. }
  37089. }
  37090. // Sides
  37091. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37092. // Result
  37093. var vertexData = new VertexData();
  37094. vertexData.indices = indices;
  37095. vertexData.positions = positions;
  37096. vertexData.normals = normals;
  37097. vertexData.uvs = uvs;
  37098. return vertexData;
  37099. };
  37100. /**
  37101. * Creates the VertexData of the LineSystem
  37102. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37103. * - lines an array of lines, each line being an array of successive Vector3
  37104. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37105. * @returns the VertexData of the LineSystem
  37106. */
  37107. VertexData.CreateLineSystem = function (options) {
  37108. var indices = [];
  37109. var positions = [];
  37110. var lines = options.lines;
  37111. var colors = options.colors;
  37112. var vertexColors = [];
  37113. var idx = 0;
  37114. for (var l = 0; l < lines.length; l++) {
  37115. var points = lines[l];
  37116. for (var index = 0; index < points.length; index++) {
  37117. positions.push(points[index].x, points[index].y, points[index].z);
  37118. if (colors) {
  37119. var color = colors[l];
  37120. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37121. }
  37122. if (index > 0) {
  37123. indices.push(idx - 1);
  37124. indices.push(idx);
  37125. }
  37126. idx++;
  37127. }
  37128. }
  37129. var vertexData = new VertexData();
  37130. vertexData.indices = indices;
  37131. vertexData.positions = positions;
  37132. if (colors) {
  37133. vertexData.colors = vertexColors;
  37134. }
  37135. return vertexData;
  37136. };
  37137. /**
  37138. * Create the VertexData for a DashedLines
  37139. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37140. * - points an array successive Vector3
  37141. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37142. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37143. * - dashNb the intended total number of dashes, optional, default 200
  37144. * @returns the VertexData for the DashedLines
  37145. */
  37146. VertexData.CreateDashedLines = function (options) {
  37147. var dashSize = options.dashSize || 3;
  37148. var gapSize = options.gapSize || 1;
  37149. var dashNb = options.dashNb || 200;
  37150. var points = options.points;
  37151. var positions = new Array();
  37152. var indices = new Array();
  37153. var curvect = BABYLON.Vector3.Zero();
  37154. var lg = 0;
  37155. var nb = 0;
  37156. var shft = 0;
  37157. var dashshft = 0;
  37158. var curshft = 0;
  37159. var idx = 0;
  37160. var i = 0;
  37161. for (i = 0; i < points.length - 1; i++) {
  37162. points[i + 1].subtractToRef(points[i], curvect);
  37163. lg += curvect.length();
  37164. }
  37165. shft = lg / dashNb;
  37166. dashshft = dashSize * shft / (dashSize + gapSize);
  37167. for (i = 0; i < points.length - 1; i++) {
  37168. points[i + 1].subtractToRef(points[i], curvect);
  37169. nb = Math.floor(curvect.length() / shft);
  37170. curvect.normalize();
  37171. for (var j = 0; j < nb; j++) {
  37172. curshft = shft * j;
  37173. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37174. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37175. indices.push(idx, idx + 1);
  37176. idx += 2;
  37177. }
  37178. }
  37179. // Result
  37180. var vertexData = new VertexData();
  37181. vertexData.positions = positions;
  37182. vertexData.indices = indices;
  37183. return vertexData;
  37184. };
  37185. /**
  37186. * Creates the VertexData for a Ground
  37187. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37188. * - width the width (x direction) of the ground, optional, default 1
  37189. * - height the height (z direction) of the ground, optional, default 1
  37190. * - subdivisions the number of subdivisions per side, optional, default 1
  37191. * @returns the VertexData of the Ground
  37192. */
  37193. VertexData.CreateGround = function (options) {
  37194. var indices = [];
  37195. var positions = [];
  37196. var normals = [];
  37197. var uvs = [];
  37198. var row, col;
  37199. var width = options.width || 1;
  37200. var height = options.height || 1;
  37201. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37202. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37203. for (row = 0; row <= subdivisionsY; row++) {
  37204. for (col = 0; col <= subdivisionsX; col++) {
  37205. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37206. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37207. positions.push(position.x, position.y, position.z);
  37208. normals.push(normal.x, normal.y, normal.z);
  37209. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37210. }
  37211. }
  37212. for (row = 0; row < subdivisionsY; row++) {
  37213. for (col = 0; col < subdivisionsX; col++) {
  37214. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37215. indices.push(col + 1 + row * (subdivisionsX + 1));
  37216. indices.push(col + row * (subdivisionsX + 1));
  37217. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37218. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37219. indices.push(col + row * (subdivisionsX + 1));
  37220. }
  37221. }
  37222. // Result
  37223. var vertexData = new VertexData();
  37224. vertexData.indices = indices;
  37225. vertexData.positions = positions;
  37226. vertexData.normals = normals;
  37227. vertexData.uvs = uvs;
  37228. return vertexData;
  37229. };
  37230. /**
  37231. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37232. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37233. * * xmin the ground minimum X coordinate, optional, default -1
  37234. * * zmin the ground minimum Z coordinate, optional, default -1
  37235. * * xmax the ground maximum X coordinate, optional, default 1
  37236. * * zmax the ground maximum Z coordinate, optional, default 1
  37237. * * 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}
  37238. * * 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}
  37239. * @returns the VertexData of the TiledGround
  37240. */
  37241. VertexData.CreateTiledGround = function (options) {
  37242. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37243. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37244. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37245. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37246. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37247. var precision = options.precision || { w: 1, h: 1 };
  37248. var indices = new Array();
  37249. var positions = new Array();
  37250. var normals = new Array();
  37251. var uvs = new Array();
  37252. var row, col, tileRow, tileCol;
  37253. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37254. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37255. precision.w = (precision.w < 1) ? 1 : precision.w;
  37256. precision.h = (precision.h < 1) ? 1 : precision.h;
  37257. var tileSize = {
  37258. 'w': (xmax - xmin) / subdivisions.w,
  37259. 'h': (zmax - zmin) / subdivisions.h
  37260. };
  37261. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37262. // Indices
  37263. var base = positions.length / 3;
  37264. var rowLength = precision.w + 1;
  37265. for (row = 0; row < precision.h; row++) {
  37266. for (col = 0; col < precision.w; col++) {
  37267. var square = [
  37268. base + col + row * rowLength,
  37269. base + (col + 1) + row * rowLength,
  37270. base + (col + 1) + (row + 1) * rowLength,
  37271. base + col + (row + 1) * rowLength
  37272. ];
  37273. indices.push(square[1]);
  37274. indices.push(square[2]);
  37275. indices.push(square[3]);
  37276. indices.push(square[0]);
  37277. indices.push(square[1]);
  37278. indices.push(square[3]);
  37279. }
  37280. }
  37281. // Position, normals and uvs
  37282. var position = BABYLON.Vector3.Zero();
  37283. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37284. for (row = 0; row <= precision.h; row++) {
  37285. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37286. for (col = 0; col <= precision.w; col++) {
  37287. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37288. position.y = 0;
  37289. positions.push(position.x, position.y, position.z);
  37290. normals.push(normal.x, normal.y, normal.z);
  37291. uvs.push(col / precision.w, row / precision.h);
  37292. }
  37293. }
  37294. }
  37295. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37296. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37297. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37298. }
  37299. }
  37300. // Result
  37301. var vertexData = new VertexData();
  37302. vertexData.indices = indices;
  37303. vertexData.positions = positions;
  37304. vertexData.normals = normals;
  37305. vertexData.uvs = uvs;
  37306. return vertexData;
  37307. };
  37308. /**
  37309. * Creates the VertexData of the Ground designed from a heightmap
  37310. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37311. * * width the width (x direction) of the ground
  37312. * * height the height (z direction) of the ground
  37313. * * subdivisions the number of subdivisions per side
  37314. * * minHeight the minimum altitude on the ground, optional, default 0
  37315. * * maxHeight the maximum altitude on the ground, optional default 1
  37316. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37317. * * buffer the array holding the image color data
  37318. * * bufferWidth the width of image
  37319. * * bufferHeight the height of image
  37320. * @returns the VertexData of the Ground designed from a heightmap
  37321. */
  37322. VertexData.CreateGroundFromHeightMap = function (options) {
  37323. var indices = [];
  37324. var positions = [];
  37325. var normals = [];
  37326. var uvs = [];
  37327. var row, col;
  37328. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37329. // Vertices
  37330. for (row = 0; row <= options.subdivisions; row++) {
  37331. for (col = 0; col <= options.subdivisions; col++) {
  37332. 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));
  37333. // Compute height
  37334. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37335. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37336. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37337. var r = options.buffer[pos] / 255.0;
  37338. var g = options.buffer[pos + 1] / 255.0;
  37339. var b = options.buffer[pos + 2] / 255.0;
  37340. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37341. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37342. // Add vertex
  37343. positions.push(position.x, position.y, position.z);
  37344. normals.push(0, 0, 0);
  37345. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37346. }
  37347. }
  37348. // Indices
  37349. for (row = 0; row < options.subdivisions; row++) {
  37350. for (col = 0; col < options.subdivisions; col++) {
  37351. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37352. indices.push(col + 1 + row * (options.subdivisions + 1));
  37353. indices.push(col + row * (options.subdivisions + 1));
  37354. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37355. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37356. indices.push(col + row * (options.subdivisions + 1));
  37357. }
  37358. }
  37359. // Normals
  37360. VertexData.ComputeNormals(positions, indices, normals);
  37361. // Result
  37362. var vertexData = new VertexData();
  37363. vertexData.indices = indices;
  37364. vertexData.positions = positions;
  37365. vertexData.normals = normals;
  37366. vertexData.uvs = uvs;
  37367. return vertexData;
  37368. };
  37369. /**
  37370. * Creates the VertexData for a Plane
  37371. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37372. * * size sets the width and height of the plane to the value of size, optional default 1
  37373. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37374. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37375. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37376. * * 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)
  37377. * * 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)
  37378. * @returns the VertexData of the box
  37379. */
  37380. VertexData.CreatePlane = function (options) {
  37381. var indices = [];
  37382. var positions = [];
  37383. var normals = [];
  37384. var uvs = [];
  37385. var width = options.width || options.size || 1;
  37386. var height = options.height || options.size || 1;
  37387. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37388. // Vertices
  37389. var halfWidth = width / 2.0;
  37390. var halfHeight = height / 2.0;
  37391. positions.push(-halfWidth, -halfHeight, 0);
  37392. normals.push(0, 0, -1.0);
  37393. uvs.push(0.0, 0.0);
  37394. positions.push(halfWidth, -halfHeight, 0);
  37395. normals.push(0, 0, -1.0);
  37396. uvs.push(1.0, 0.0);
  37397. positions.push(halfWidth, halfHeight, 0);
  37398. normals.push(0, 0, -1.0);
  37399. uvs.push(1.0, 1.0);
  37400. positions.push(-halfWidth, halfHeight, 0);
  37401. normals.push(0, 0, -1.0);
  37402. uvs.push(0.0, 1.0);
  37403. // Indices
  37404. indices.push(0);
  37405. indices.push(1);
  37406. indices.push(2);
  37407. indices.push(0);
  37408. indices.push(2);
  37409. indices.push(3);
  37410. // Sides
  37411. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37412. // Result
  37413. var vertexData = new VertexData();
  37414. vertexData.indices = indices;
  37415. vertexData.positions = positions;
  37416. vertexData.normals = normals;
  37417. vertexData.uvs = uvs;
  37418. return vertexData;
  37419. };
  37420. /**
  37421. * Creates the VertexData of the Disc or regular Polygon
  37422. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37423. * * radius the radius of the disc, optional default 0.5
  37424. * * tessellation the number of polygon sides, optional, default 64
  37425. * * 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
  37426. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37427. * * 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)
  37428. * * 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)
  37429. * @returns the VertexData of the box
  37430. */
  37431. VertexData.CreateDisc = function (options) {
  37432. var positions = new Array();
  37433. var indices = new Array();
  37434. var normals = new Array();
  37435. var uvs = new Array();
  37436. var radius = options.radius || 0.5;
  37437. var tessellation = options.tessellation || 64;
  37438. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37439. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37440. // positions and uvs
  37441. positions.push(0, 0, 0); // disc center first
  37442. uvs.push(0.5, 0.5);
  37443. var theta = Math.PI * 2 * arc;
  37444. var step = theta / tessellation;
  37445. for (var a = 0; a < theta; a += step) {
  37446. var x = Math.cos(a);
  37447. var y = Math.sin(a);
  37448. var u = (x + 1) / 2;
  37449. var v = (1 - y) / 2;
  37450. positions.push(radius * x, radius * y, 0);
  37451. uvs.push(u, v);
  37452. }
  37453. if (arc === 1) {
  37454. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37455. uvs.push(uvs[2], uvs[3]);
  37456. }
  37457. //indices
  37458. var vertexNb = positions.length / 3;
  37459. for (var i = 1; i < vertexNb - 1; i++) {
  37460. indices.push(i + 1, 0, i);
  37461. }
  37462. // result
  37463. VertexData.ComputeNormals(positions, indices, normals);
  37464. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37465. var vertexData = new VertexData();
  37466. vertexData.indices = indices;
  37467. vertexData.positions = positions;
  37468. vertexData.normals = normals;
  37469. vertexData.uvs = uvs;
  37470. return vertexData;
  37471. };
  37472. /**
  37473. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37474. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37475. * @param polygon a mesh built from polygonTriangulation.build()
  37476. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37477. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37478. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37479. * @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)
  37480. * @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)
  37481. * @returns the VertexData of the Polygon
  37482. */
  37483. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37484. var faceUV = fUV || new Array(3);
  37485. var faceColors = fColors;
  37486. var colors = [];
  37487. // default face colors and UV if undefined
  37488. for (var f = 0; f < 3; f++) {
  37489. if (faceUV[f] === undefined) {
  37490. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37491. }
  37492. if (faceColors && faceColors[f] === undefined) {
  37493. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37494. }
  37495. }
  37496. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37497. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37498. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37499. var indices = polygon.getIndices();
  37500. // set face colours and textures
  37501. var idx = 0;
  37502. var face = 0;
  37503. for (var index = 0; index < normals.length; index += 3) {
  37504. //Edge Face no. 1
  37505. if (Math.abs(normals[index + 1]) < 0.001) {
  37506. face = 1;
  37507. }
  37508. //Top Face no. 0
  37509. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37510. face = 0;
  37511. }
  37512. //Bottom Face no. 2
  37513. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37514. face = 2;
  37515. }
  37516. idx = index / 3;
  37517. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37518. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37519. if (faceColors) {
  37520. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37521. }
  37522. }
  37523. // sides
  37524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37525. // Result
  37526. var vertexData = new VertexData();
  37527. vertexData.indices = indices;
  37528. vertexData.positions = positions;
  37529. vertexData.normals = normals;
  37530. vertexData.uvs = uvs;
  37531. if (faceColors) {
  37532. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37533. vertexData.colors = totalColors;
  37534. }
  37535. return vertexData;
  37536. };
  37537. /**
  37538. * Creates the VertexData of the IcoSphere
  37539. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37540. * * radius the radius of the IcoSphere, optional default 1
  37541. * * radiusX allows stretching in the x direction, optional, default radius
  37542. * * radiusY allows stretching in the y direction, optional, default radius
  37543. * * radiusZ allows stretching in the z direction, optional, default radius
  37544. * * flat when true creates a flat shaded mesh, optional, default true
  37545. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37546. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37547. * * 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)
  37548. * * 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)
  37549. * @returns the VertexData of the IcoSphere
  37550. */
  37551. VertexData.CreateIcoSphere = function (options) {
  37552. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37553. var radius = options.radius || 1;
  37554. var flat = (options.flat === undefined) ? true : options.flat;
  37555. var subdivisions = options.subdivisions || 4;
  37556. var radiusX = options.radiusX || radius;
  37557. var radiusY = options.radiusY || radius;
  37558. var radiusZ = options.radiusZ || radius;
  37559. var t = (1 + Math.sqrt(5)) / 2;
  37560. // 12 vertex x,y,z
  37561. var ico_vertices = [
  37562. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37563. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37564. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37565. ];
  37566. // index of 3 vertex makes a face of icopshere
  37567. var ico_indices = [
  37568. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37569. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37570. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37571. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37572. ];
  37573. // vertex for uv have aliased position, not for UV
  37574. var vertices_unalias_id = [
  37575. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37576. // vertex alias
  37577. 0,
  37578. 2,
  37579. 3,
  37580. 3,
  37581. 3,
  37582. 4,
  37583. 7,
  37584. 8,
  37585. 9,
  37586. 9,
  37587. 10,
  37588. 11 // 23: B + 12
  37589. ];
  37590. // uv as integer step (not pixels !)
  37591. var ico_vertexuv = [
  37592. 5, 1, 3, 1, 6, 4, 0, 0,
  37593. 5, 3, 4, 2, 2, 2, 4, 0,
  37594. 2, 0, 1, 1, 6, 0, 6, 2,
  37595. // vertex alias (for same vertex on different faces)
  37596. 0, 4,
  37597. 3, 3,
  37598. 4, 4,
  37599. 3, 1,
  37600. 4, 2,
  37601. 4, 4,
  37602. 0, 2,
  37603. 1, 1,
  37604. 2, 2,
  37605. 3, 3,
  37606. 1, 3,
  37607. 2, 4 // 23: B + 12
  37608. ];
  37609. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37610. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37611. // First island of uv mapping
  37612. // v = 4h 3+ 2
  37613. // v = 3h 9+ 4
  37614. // v = 2h 9+ 5 B
  37615. // v = 1h 9 1 0
  37616. // v = 0h 3 8 7 A
  37617. // u = 0 1 2 3 4 5 6 *a
  37618. // Second island of uv mapping
  37619. // v = 4h 0+ B+ 4+
  37620. // v = 3h A+ 2+
  37621. // v = 2h 7+ 6 3+
  37622. // v = 1h 8+ 3+
  37623. // v = 0h
  37624. // u = 0 1 2 3 4 5 6 *a
  37625. // Face layout on texture UV mapping
  37626. // ============
  37627. // \ 4 /\ 16 / ======
  37628. // \ / \ / /\ 11 /
  37629. // \/ 7 \/ / \ /
  37630. // ======= / 10 \/
  37631. // /\ 17 /\ =======
  37632. // / \ / \ \ 15 /\
  37633. // / 8 \/ 12 \ \ / \
  37634. // ============ \/ 6 \
  37635. // \ 18 /\ ============
  37636. // \ / \ \ 5 /\ 0 /
  37637. // \/ 13 \ \ / \ /
  37638. // ======= \/ 1 \/
  37639. // =============
  37640. // /\ 19 /\ 2 /\
  37641. // / \ / \ / \
  37642. // / 14 \/ 9 \/ 3 \
  37643. // ===================
  37644. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37645. var ustep = 138 / 1024;
  37646. var vstep = 239 / 1024;
  37647. var uoffset = 60 / 1024;
  37648. var voffset = 26 / 1024;
  37649. // Second island should have margin, not to touch the first island
  37650. // avoid any borderline artefact in pixel rounding
  37651. var island_u_offset = -40 / 1024;
  37652. var island_v_offset = +20 / 1024;
  37653. // face is either island 0 or 1 :
  37654. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37655. var island = [
  37656. 0, 0, 0, 0, 1,
  37657. 0, 0, 1, 1, 0,
  37658. 0, 0, 1, 1, 0,
  37659. 0, 1, 1, 1, 0 // 15 - 19
  37660. ];
  37661. var indices = new Array();
  37662. var positions = new Array();
  37663. var normals = new Array();
  37664. var uvs = new Array();
  37665. var current_indice = 0;
  37666. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37667. var face_vertex_pos = new Array(3);
  37668. var face_vertex_uv = new Array(3);
  37669. var v012;
  37670. for (v012 = 0; v012 < 3; v012++) {
  37671. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37672. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37673. }
  37674. // create all with normals
  37675. for (var face = 0; face < 20; face++) {
  37676. // 3 vertex per face
  37677. for (v012 = 0; v012 < 3; v012++) {
  37678. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37679. var v_id = ico_indices[3 * face + v012];
  37680. // vertex have 3D position (x,y,z)
  37681. 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]);
  37682. // Normalize to get normal, then scale to radius
  37683. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37684. // uv Coordinates from vertex ID
  37685. 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);
  37686. }
  37687. // Subdivide the face (interpolate pos, norm, uv)
  37688. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37689. // - norm is linear interpolation of vertex corner normal
  37690. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37691. // - uv is linear interpolation
  37692. //
  37693. // Topology is as below for sub-divide by 2
  37694. // vertex shown as v0,v1,v2
  37695. // interp index is i1 to progress in range [v0,v1[
  37696. // interp index is i2 to progress in range [v0,v2[
  37697. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37698. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37699. //
  37700. //
  37701. // i2 v2
  37702. // ^ ^
  37703. // / / \
  37704. // / / \
  37705. // / / \
  37706. // / / (0,1) \
  37707. // / #---------\
  37708. // / / \ (0,0)'/ \
  37709. // / / \ / \
  37710. // / / \ / \
  37711. // / / (0,0) \ / (1,0) \
  37712. // / #---------#---------\
  37713. // v0 v1
  37714. //
  37715. // --------------------> i1
  37716. //
  37717. // interp of (i1,i2):
  37718. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37719. // along i1 : lerp(x0,x1, i1/(S-i2))
  37720. //
  37721. // centroid of triangle is needed to get help normal computation
  37722. // (c1,c2) are used for centroid location
  37723. var interp_vertex = function (i1, i2, c1, c2) {
  37724. // vertex is interpolated from
  37725. // - face_vertex_pos[0..2]
  37726. // - face_vertex_uv[0..2]
  37727. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37728. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37729. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37730. pos_interp.normalize();
  37731. var vertex_normal;
  37732. if (flat) {
  37733. // in flat mode, recalculate normal as face centroid normal
  37734. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37735. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37736. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37737. }
  37738. else {
  37739. // in smooth mode, recalculate normal from each single vertex position
  37740. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37741. }
  37742. // Vertex normal need correction due to X,Y,Z radius scaling
  37743. vertex_normal.x /= radiusX;
  37744. vertex_normal.y /= radiusY;
  37745. vertex_normal.z /= radiusZ;
  37746. vertex_normal.normalize();
  37747. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37748. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37749. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37750. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37751. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37752. uvs.push(uv_interp.x, uv_interp.y);
  37753. // push each vertex has member of a face
  37754. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37755. indices.push(current_indice);
  37756. current_indice++;
  37757. };
  37758. for (var i2 = 0; i2 < subdivisions; i2++) {
  37759. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37760. // face : (i1,i2) for /\ :
  37761. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37762. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37763. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37764. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37765. if (i1 + i2 + 1 < subdivisions) {
  37766. // face : (i1,i2)' for \/ :
  37767. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37768. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37769. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37770. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37771. }
  37772. }
  37773. }
  37774. }
  37775. // Sides
  37776. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37777. // Result
  37778. var vertexData = new VertexData();
  37779. vertexData.indices = indices;
  37780. vertexData.positions = positions;
  37781. vertexData.normals = normals;
  37782. vertexData.uvs = uvs;
  37783. return vertexData;
  37784. };
  37785. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37786. /**
  37787. * Creates the VertexData for a Polyhedron
  37788. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37789. * * type provided types are:
  37790. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37791. * * 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)
  37792. * * size the size of the IcoSphere, optional default 1
  37793. * * sizeX allows stretching in the x direction, optional, default size
  37794. * * sizeY allows stretching in the y direction, optional, default size
  37795. * * sizeZ allows stretching in the z direction, optional, default size
  37796. * * 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
  37797. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37798. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37799. * * flat when true creates a flat shaded mesh, optional, default true
  37800. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37801. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37802. * * 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)
  37803. * * 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)
  37804. * @returns the VertexData of the Polyhedron
  37805. */
  37806. VertexData.CreatePolyhedron = function (options) {
  37807. // provided polyhedron types :
  37808. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37809. // 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)
  37810. var polyhedra = [];
  37811. 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]] };
  37812. 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]] };
  37813. polyhedra[2] = {
  37814. 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]],
  37815. 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]]
  37816. };
  37817. polyhedra[3] = {
  37818. 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]],
  37819. 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]]
  37820. };
  37821. polyhedra[4] = {
  37822. 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]],
  37823. 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]]
  37824. };
  37825. 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]] };
  37826. 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]] };
  37827. 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]] };
  37828. 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]] };
  37829. 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]] };
  37830. 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]] };
  37831. 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]] };
  37832. 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]] };
  37833. 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]] };
  37834. polyhedra[14] = {
  37835. 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]],
  37836. 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]]
  37837. };
  37838. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37839. var size = options.size;
  37840. var sizeX = options.sizeX || size || 1;
  37841. var sizeY = options.sizeY || size || 1;
  37842. var sizeZ = options.sizeZ || size || 1;
  37843. var data = options.custom || polyhedra[type];
  37844. var nbfaces = data.face.length;
  37845. var faceUV = options.faceUV || new Array(nbfaces);
  37846. var faceColors = options.faceColors;
  37847. var flat = (options.flat === undefined) ? true : options.flat;
  37848. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37849. var positions = new Array();
  37850. var indices = new Array();
  37851. var normals = new Array();
  37852. var uvs = new Array();
  37853. var colors = new Array();
  37854. var index = 0;
  37855. var faceIdx = 0; // face cursor in the array "indexes"
  37856. var indexes = new Array();
  37857. var i = 0;
  37858. var f = 0;
  37859. var u, v, ang, x, y, tmp;
  37860. // default face colors and UV if undefined
  37861. if (flat) {
  37862. for (f = 0; f < nbfaces; f++) {
  37863. if (faceColors && faceColors[f] === undefined) {
  37864. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37865. }
  37866. if (faceUV && faceUV[f] === undefined) {
  37867. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37868. }
  37869. }
  37870. }
  37871. if (!flat) {
  37872. for (i = 0; i < data.vertex.length; i++) {
  37873. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37874. uvs.push(0, 0);
  37875. }
  37876. for (f = 0; f < nbfaces; f++) {
  37877. for (i = 0; i < data.face[f].length - 2; i++) {
  37878. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37879. }
  37880. }
  37881. }
  37882. else {
  37883. for (f = 0; f < nbfaces; f++) {
  37884. var fl = data.face[f].length; // number of vertices of the current face
  37885. ang = 2 * Math.PI / fl;
  37886. x = 0.5 * Math.tan(ang / 2);
  37887. y = 0.5;
  37888. // positions, uvs, colors
  37889. for (i = 0; i < fl; i++) {
  37890. // positions
  37891. 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);
  37892. indexes.push(index);
  37893. index++;
  37894. // uvs
  37895. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37896. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37897. uvs.push(u, v);
  37898. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37899. y = x * Math.sin(ang) + y * Math.cos(ang);
  37900. x = tmp;
  37901. // colors
  37902. if (faceColors) {
  37903. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37904. }
  37905. }
  37906. // indices from indexes
  37907. for (i = 0; i < fl - 2; i++) {
  37908. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37909. }
  37910. faceIdx += fl;
  37911. }
  37912. }
  37913. VertexData.ComputeNormals(positions, indices, normals);
  37914. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37915. var vertexData = new VertexData();
  37916. vertexData.positions = positions;
  37917. vertexData.indices = indices;
  37918. vertexData.normals = normals;
  37919. vertexData.uvs = uvs;
  37920. if (faceColors && flat) {
  37921. vertexData.colors = colors;
  37922. }
  37923. return vertexData;
  37924. };
  37925. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37926. /**
  37927. * Creates the VertexData for a TorusKnot
  37928. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37929. * * radius the radius of the torus knot, optional, default 2
  37930. * * tube the thickness of the tube, optional, default 0.5
  37931. * * radialSegments the number of sides on each tube segments, optional, default 32
  37932. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37933. * * p the number of windings around the z axis, optional, default 2
  37934. * * q the number of windings around the x axis, optional, default 3
  37935. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37936. * * 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)
  37937. * * 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)
  37938. * @returns the VertexData of the Torus Knot
  37939. */
  37940. VertexData.CreateTorusKnot = function (options) {
  37941. var indices = new Array();
  37942. var positions = new Array();
  37943. var normals = new Array();
  37944. var uvs = new Array();
  37945. var radius = options.radius || 2;
  37946. var tube = options.tube || 0.5;
  37947. var radialSegments = options.radialSegments || 32;
  37948. var tubularSegments = options.tubularSegments || 32;
  37949. var p = options.p || 2;
  37950. var q = options.q || 3;
  37951. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37952. // Helper
  37953. var getPos = function (angle) {
  37954. var cu = Math.cos(angle);
  37955. var su = Math.sin(angle);
  37956. var quOverP = q / p * angle;
  37957. var cs = Math.cos(quOverP);
  37958. var tx = radius * (2 + cs) * 0.5 * cu;
  37959. var ty = radius * (2 + cs) * su * 0.5;
  37960. var tz = radius * Math.sin(quOverP) * 0.5;
  37961. return new BABYLON.Vector3(tx, ty, tz);
  37962. };
  37963. // Vertices
  37964. var i;
  37965. var j;
  37966. for (i = 0; i <= radialSegments; i++) {
  37967. var modI = i % radialSegments;
  37968. var u = modI / radialSegments * 2 * p * Math.PI;
  37969. var p1 = getPos(u);
  37970. var p2 = getPos(u + 0.01);
  37971. var tang = p2.subtract(p1);
  37972. var n = p2.add(p1);
  37973. var bitan = BABYLON.Vector3.Cross(tang, n);
  37974. n = BABYLON.Vector3.Cross(bitan, tang);
  37975. bitan.normalize();
  37976. n.normalize();
  37977. for (j = 0; j < tubularSegments; j++) {
  37978. var modJ = j % tubularSegments;
  37979. var v = modJ / tubularSegments * 2 * Math.PI;
  37980. var cx = -tube * Math.cos(v);
  37981. var cy = tube * Math.sin(v);
  37982. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37983. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37984. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37985. uvs.push(i / radialSegments);
  37986. uvs.push(j / tubularSegments);
  37987. }
  37988. }
  37989. for (i = 0; i < radialSegments; i++) {
  37990. for (j = 0; j < tubularSegments; j++) {
  37991. var jNext = (j + 1) % tubularSegments;
  37992. var a = i * tubularSegments + j;
  37993. var b = (i + 1) * tubularSegments + j;
  37994. var c = (i + 1) * tubularSegments + jNext;
  37995. var d = i * tubularSegments + jNext;
  37996. indices.push(d);
  37997. indices.push(b);
  37998. indices.push(a);
  37999. indices.push(d);
  38000. indices.push(c);
  38001. indices.push(b);
  38002. }
  38003. }
  38004. // Normals
  38005. VertexData.ComputeNormals(positions, indices, normals);
  38006. // Sides
  38007. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38008. // Result
  38009. var vertexData = new VertexData();
  38010. vertexData.indices = indices;
  38011. vertexData.positions = positions;
  38012. vertexData.normals = normals;
  38013. vertexData.uvs = uvs;
  38014. return vertexData;
  38015. };
  38016. // Tools
  38017. /**
  38018. * Compute normals for given positions and indices
  38019. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38020. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38021. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38022. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38023. * * facetNormals : optional array of facet normals (vector3)
  38024. * * facetPositions : optional array of facet positions (vector3)
  38025. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38026. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38027. * * bInfo : optional bounding info, required for facetPartitioning computation
  38028. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38029. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38030. * * useRightHandedSystem: optional boolean to for right handed system computation
  38031. * * depthSort : optional boolean to enable the facet depth sort computation
  38032. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38033. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38034. */
  38035. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38036. // temporary scalar variables
  38037. var index = 0; // facet index
  38038. var p1p2x = 0.0; // p1p2 vector x coordinate
  38039. var p1p2y = 0.0; // p1p2 vector y coordinate
  38040. var p1p2z = 0.0; // p1p2 vector z coordinate
  38041. var p3p2x = 0.0; // p3p2 vector x coordinate
  38042. var p3p2y = 0.0; // p3p2 vector y coordinate
  38043. var p3p2z = 0.0; // p3p2 vector z coordinate
  38044. var faceNormalx = 0.0; // facet normal x coordinate
  38045. var faceNormaly = 0.0; // facet normal y coordinate
  38046. var faceNormalz = 0.0; // facet normal z coordinate
  38047. var length = 0.0; // facet normal length before normalization
  38048. var v1x = 0; // vector1 x index in the positions array
  38049. var v1y = 0; // vector1 y index in the positions array
  38050. var v1z = 0; // vector1 z index in the positions array
  38051. var v2x = 0; // vector2 x index in the positions array
  38052. var v2y = 0; // vector2 y index in the positions array
  38053. var v2z = 0; // vector2 z index in the positions array
  38054. var v3x = 0; // vector3 x index in the positions array
  38055. var v3y = 0; // vector3 y index in the positions array
  38056. var v3z = 0; // vector3 z index in the positions array
  38057. var computeFacetNormals = false;
  38058. var computeFacetPositions = false;
  38059. var computeFacetPartitioning = false;
  38060. var computeDepthSort = false;
  38061. var faceNormalSign = 1;
  38062. var ratio = 0;
  38063. var distanceTo = null;
  38064. if (options) {
  38065. computeFacetNormals = (options.facetNormals) ? true : false;
  38066. computeFacetPositions = (options.facetPositions) ? true : false;
  38067. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38068. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38069. ratio = options.ratio || 0;
  38070. computeDepthSort = (options.depthSort) ? true : false;
  38071. distanceTo = (options.distanceTo);
  38072. if (computeDepthSort) {
  38073. if (distanceTo === undefined) {
  38074. distanceTo = BABYLON.Vector3.Zero();
  38075. }
  38076. var depthSortedFacets = options.depthSortedFacets;
  38077. }
  38078. }
  38079. // facetPartitioning reinit if needed
  38080. var xSubRatio = 0;
  38081. var ySubRatio = 0;
  38082. var zSubRatio = 0;
  38083. var subSq = 0;
  38084. if (computeFacetPartitioning && options && options.bbSize) {
  38085. var ox = 0; // X partitioning index for facet position
  38086. var oy = 0; // Y partinioning index for facet position
  38087. var oz = 0; // Z partinioning index for facet position
  38088. var b1x = 0; // X partitioning index for facet v1 vertex
  38089. var b1y = 0; // Y partitioning index for facet v1 vertex
  38090. var b1z = 0; // z partitioning index for facet v1 vertex
  38091. var b2x = 0; // X partitioning index for facet v2 vertex
  38092. var b2y = 0; // Y partitioning index for facet v2 vertex
  38093. var b2z = 0; // Z partitioning index for facet v2 vertex
  38094. var b3x = 0; // X partitioning index for facet v3 vertex
  38095. var b3y = 0; // Y partitioning index for facet v3 vertex
  38096. var b3z = 0; // Z partitioning index for facet v3 vertex
  38097. var block_idx_o = 0; // facet barycenter block index
  38098. var block_idx_v1 = 0; // v1 vertex block index
  38099. var block_idx_v2 = 0; // v2 vertex block index
  38100. var block_idx_v3 = 0; // v3 vertex block index
  38101. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38102. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38103. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38104. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38105. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38106. subSq = options.subDiv.max * options.subDiv.max;
  38107. options.facetPartitioning.length = 0;
  38108. }
  38109. // reset the normals
  38110. for (index = 0; index < positions.length; index++) {
  38111. normals[index] = 0.0;
  38112. }
  38113. // Loop : 1 indice triplet = 1 facet
  38114. var nbFaces = (indices.length / 3) | 0;
  38115. for (index = 0; index < nbFaces; index++) {
  38116. // get the indexes of the coordinates of each vertex of the facet
  38117. v1x = indices[index * 3] * 3;
  38118. v1y = v1x + 1;
  38119. v1z = v1x + 2;
  38120. v2x = indices[index * 3 + 1] * 3;
  38121. v2y = v2x + 1;
  38122. v2z = v2x + 2;
  38123. v3x = indices[index * 3 + 2] * 3;
  38124. v3y = v3x + 1;
  38125. v3z = v3x + 2;
  38126. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38127. p1p2y = positions[v1y] - positions[v2y];
  38128. p1p2z = positions[v1z] - positions[v2z];
  38129. p3p2x = positions[v3x] - positions[v2x];
  38130. p3p2y = positions[v3y] - positions[v2y];
  38131. p3p2z = positions[v3z] - positions[v2z];
  38132. // compute the face normal with the cross product
  38133. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38134. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38135. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38136. // normalize this normal and store it in the array facetData
  38137. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38138. length = (length === 0) ? 1.0 : length;
  38139. faceNormalx /= length;
  38140. faceNormaly /= length;
  38141. faceNormalz /= length;
  38142. if (computeFacetNormals && options) {
  38143. options.facetNormals[index].x = faceNormalx;
  38144. options.facetNormals[index].y = faceNormaly;
  38145. options.facetNormals[index].z = faceNormalz;
  38146. }
  38147. if (computeFacetPositions && options) {
  38148. // compute and the facet barycenter coordinates in the array facetPositions
  38149. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38150. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38151. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38152. }
  38153. if (computeFacetPartitioning && options) {
  38154. // store the facet indexes in arrays in the main facetPartitioning array :
  38155. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38156. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38157. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38158. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38159. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38160. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38161. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38162. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38163. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38164. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38165. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38166. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38167. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38168. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38169. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38170. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38171. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38172. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38173. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38174. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38175. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38176. // push each facet index in each block containing the vertex
  38177. options.facetPartitioning[block_idx_v1].push(index);
  38178. if (block_idx_v2 != block_idx_v1) {
  38179. options.facetPartitioning[block_idx_v2].push(index);
  38180. }
  38181. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38182. options.facetPartitioning[block_idx_v3].push(index);
  38183. }
  38184. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38185. options.facetPartitioning[block_idx_o].push(index);
  38186. }
  38187. }
  38188. if (computeDepthSort && options && options.facetPositions) {
  38189. var dsf = depthSortedFacets[index];
  38190. dsf.ind = index * 3;
  38191. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38192. }
  38193. // compute the normals anyway
  38194. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38195. normals[v1y] += faceNormaly;
  38196. normals[v1z] += faceNormalz;
  38197. normals[v2x] += faceNormalx;
  38198. normals[v2y] += faceNormaly;
  38199. normals[v2z] += faceNormalz;
  38200. normals[v3x] += faceNormalx;
  38201. normals[v3y] += faceNormaly;
  38202. normals[v3z] += faceNormalz;
  38203. }
  38204. // last normalization of each normal
  38205. for (index = 0; index < normals.length / 3; index++) {
  38206. faceNormalx = normals[index * 3];
  38207. faceNormaly = normals[index * 3 + 1];
  38208. faceNormalz = normals[index * 3 + 2];
  38209. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38210. length = (length === 0) ? 1.0 : length;
  38211. faceNormalx /= length;
  38212. faceNormaly /= length;
  38213. faceNormalz /= length;
  38214. normals[index * 3] = faceNormalx;
  38215. normals[index * 3 + 1] = faceNormaly;
  38216. normals[index * 3 + 2] = faceNormalz;
  38217. }
  38218. };
  38219. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38220. var li = indices.length;
  38221. var ln = normals.length;
  38222. var i;
  38223. var n;
  38224. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38225. switch (sideOrientation) {
  38226. case BABYLON.Mesh.FRONTSIDE:
  38227. // nothing changed
  38228. break;
  38229. case BABYLON.Mesh.BACKSIDE:
  38230. var tmp;
  38231. // indices
  38232. for (i = 0; i < li; i += 3) {
  38233. tmp = indices[i];
  38234. indices[i] = indices[i + 2];
  38235. indices[i + 2] = tmp;
  38236. }
  38237. // normals
  38238. for (n = 0; n < ln; n++) {
  38239. normals[n] = -normals[n];
  38240. }
  38241. break;
  38242. case BABYLON.Mesh.DOUBLESIDE:
  38243. // positions
  38244. var lp = positions.length;
  38245. var l = lp / 3;
  38246. for (var p = 0; p < lp; p++) {
  38247. positions[lp + p] = positions[p];
  38248. }
  38249. // indices
  38250. for (i = 0; i < li; i += 3) {
  38251. indices[i + li] = indices[i + 2] + l;
  38252. indices[i + 1 + li] = indices[i + 1] + l;
  38253. indices[i + 2 + li] = indices[i] + l;
  38254. }
  38255. // normals
  38256. for (n = 0; n < ln; n++) {
  38257. normals[ln + n] = -normals[n];
  38258. }
  38259. // uvs
  38260. var lu = uvs.length;
  38261. var u = 0;
  38262. for (u = 0; u < lu; u++) {
  38263. uvs[u + lu] = uvs[u];
  38264. }
  38265. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38266. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38267. u = 0;
  38268. for (i = 0; i < lu / 2; i++) {
  38269. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38270. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38271. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38272. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38273. u += 2;
  38274. }
  38275. break;
  38276. }
  38277. };
  38278. /**
  38279. * Applies VertexData created from the imported parameters to the geometry
  38280. * @param parsedVertexData the parsed data from an imported file
  38281. * @param geometry the geometry to apply the VertexData to
  38282. */
  38283. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38284. var vertexData = new VertexData();
  38285. // positions
  38286. var positions = parsedVertexData.positions;
  38287. if (positions) {
  38288. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38289. }
  38290. // normals
  38291. var normals = parsedVertexData.normals;
  38292. if (normals) {
  38293. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38294. }
  38295. // tangents
  38296. var tangents = parsedVertexData.tangents;
  38297. if (tangents) {
  38298. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38299. }
  38300. // uvs
  38301. var uvs = parsedVertexData.uvs;
  38302. if (uvs) {
  38303. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38304. }
  38305. // uv2s
  38306. var uv2s = parsedVertexData.uv2s;
  38307. if (uv2s) {
  38308. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38309. }
  38310. // uv3s
  38311. var uv3s = parsedVertexData.uv3s;
  38312. if (uv3s) {
  38313. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38314. }
  38315. // uv4s
  38316. var uv4s = parsedVertexData.uv4s;
  38317. if (uv4s) {
  38318. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38319. }
  38320. // uv5s
  38321. var uv5s = parsedVertexData.uv5s;
  38322. if (uv5s) {
  38323. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38324. }
  38325. // uv6s
  38326. var uv6s = parsedVertexData.uv6s;
  38327. if (uv6s) {
  38328. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38329. }
  38330. // colors
  38331. var colors = parsedVertexData.colors;
  38332. if (colors) {
  38333. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38334. }
  38335. // matricesIndices
  38336. var matricesIndices = parsedVertexData.matricesIndices;
  38337. if (matricesIndices) {
  38338. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38339. }
  38340. // matricesWeights
  38341. var matricesWeights = parsedVertexData.matricesWeights;
  38342. if (matricesWeights) {
  38343. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38344. }
  38345. // indices
  38346. var indices = parsedVertexData.indices;
  38347. if (indices) {
  38348. vertexData.indices = indices;
  38349. }
  38350. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38351. };
  38352. return VertexData;
  38353. }());
  38354. BABYLON.VertexData = VertexData;
  38355. })(BABYLON || (BABYLON = {}));
  38356. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38357. var BABYLON;
  38358. (function (BABYLON) {
  38359. /**
  38360. * Class used to store geometry data (vertex buffers + index buffer)
  38361. */
  38362. var Geometry = /** @class */ (function () {
  38363. /**
  38364. * Creates a new geometry
  38365. * @param id defines the unique ID
  38366. * @param scene defines the hosting scene
  38367. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38368. * @param updatable defines if geometry must be updatable (false by default)
  38369. * @param mesh defines the mesh that will be associated with the geometry
  38370. */
  38371. function Geometry(id, scene, vertexData, updatable, mesh) {
  38372. if (updatable === void 0) { updatable = false; }
  38373. if (mesh === void 0) { mesh = null; }
  38374. /**
  38375. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38376. */
  38377. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38378. this._totalVertices = 0;
  38379. this._isDisposed = false;
  38380. this._indexBufferIsUpdatable = false;
  38381. this.id = id;
  38382. this._engine = scene.getEngine();
  38383. this._meshes = [];
  38384. this._scene = scene;
  38385. //Init vertex buffer cache
  38386. this._vertexBuffers = {};
  38387. this._indices = [];
  38388. this._updatable = updatable;
  38389. // vertexData
  38390. if (vertexData) {
  38391. this.setAllVerticesData(vertexData, updatable);
  38392. }
  38393. else {
  38394. this._totalVertices = 0;
  38395. this._indices = [];
  38396. }
  38397. if (this._engine.getCaps().vertexArrayObject) {
  38398. this._vertexArrayObjects = {};
  38399. }
  38400. // applyToMesh
  38401. if (mesh) {
  38402. if (mesh.getClassName() === "LinesMesh") {
  38403. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38404. this._updateExtend();
  38405. }
  38406. this.applyToMesh(mesh);
  38407. mesh.computeWorldMatrix(true);
  38408. }
  38409. }
  38410. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38411. /**
  38412. * 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
  38413. */
  38414. get: function () {
  38415. return this._boundingBias;
  38416. },
  38417. /**
  38418. * 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
  38419. */
  38420. set: function (value) {
  38421. if (this._boundingBias && this._boundingBias.equals(value)) {
  38422. return;
  38423. }
  38424. this._boundingBias = value.clone();
  38425. this._updateBoundingInfo(true, null);
  38426. },
  38427. enumerable: true,
  38428. configurable: true
  38429. });
  38430. /**
  38431. * Static function used to attach a new empty geometry to a mesh
  38432. * @param mesh defines the mesh to attach the geometry to
  38433. * @returns the new {BABYLON.Geometry}
  38434. */
  38435. Geometry.CreateGeometryForMesh = function (mesh) {
  38436. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38437. geometry.applyToMesh(mesh);
  38438. return geometry;
  38439. };
  38440. Object.defineProperty(Geometry.prototype, "extend", {
  38441. /**
  38442. * Gets the current extend of the geometry
  38443. */
  38444. get: function () {
  38445. return this._extend;
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. /**
  38451. * Gets the hosting scene
  38452. * @returns the hosting {BABYLON.Scene}
  38453. */
  38454. Geometry.prototype.getScene = function () {
  38455. return this._scene;
  38456. };
  38457. /**
  38458. * Gets the hosting engine
  38459. * @returns the hosting {BABYLON.Engine}
  38460. */
  38461. Geometry.prototype.getEngine = function () {
  38462. return this._engine;
  38463. };
  38464. /**
  38465. * Defines if the geometry is ready to use
  38466. * @returns true if the geometry is ready to be used
  38467. */
  38468. Geometry.prototype.isReady = function () {
  38469. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38470. };
  38471. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38472. /**
  38473. * Gets a value indicating that the geometry should not be serialized
  38474. */
  38475. get: function () {
  38476. for (var index = 0; index < this._meshes.length; index++) {
  38477. if (!this._meshes[index].doNotSerialize) {
  38478. return false;
  38479. }
  38480. }
  38481. return true;
  38482. },
  38483. enumerable: true,
  38484. configurable: true
  38485. });
  38486. /** @hidden */
  38487. Geometry.prototype._rebuild = function () {
  38488. if (this._vertexArrayObjects) {
  38489. this._vertexArrayObjects = {};
  38490. }
  38491. // Index buffer
  38492. if (this._meshes.length !== 0 && this._indices) {
  38493. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38494. }
  38495. // Vertex buffers
  38496. for (var key in this._vertexBuffers) {
  38497. var vertexBuffer = this._vertexBuffers[key];
  38498. vertexBuffer._rebuild();
  38499. }
  38500. };
  38501. /**
  38502. * Affects all gemetry data in one call
  38503. * @param vertexData defines the geometry data
  38504. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38505. */
  38506. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38507. vertexData.applyToGeometry(this, updatable);
  38508. this.notifyUpdate();
  38509. };
  38510. /**
  38511. * Set specific vertex data
  38512. * @param kind defines the data kind (Position, normal, etc...)
  38513. * @param data defines the vertex data to use
  38514. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38515. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38516. */
  38517. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38518. if (updatable === void 0) { updatable = false; }
  38519. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38520. this.setVerticesBuffer(buffer);
  38521. };
  38522. /**
  38523. * Removes a specific vertex data
  38524. * @param kind defines the data kind (Position, normal, etc...)
  38525. */
  38526. Geometry.prototype.removeVerticesData = function (kind) {
  38527. if (this._vertexBuffers[kind]) {
  38528. this._vertexBuffers[kind].dispose();
  38529. delete this._vertexBuffers[kind];
  38530. }
  38531. };
  38532. /**
  38533. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38534. * @param buffer defines the vertex buffer to use
  38535. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38536. */
  38537. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38538. if (totalVertices === void 0) { totalVertices = null; }
  38539. var kind = buffer.getKind();
  38540. if (this._vertexBuffers[kind]) {
  38541. this._vertexBuffers[kind].dispose();
  38542. }
  38543. this._vertexBuffers[kind] = buffer;
  38544. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38545. var data = buffer.getData();
  38546. if (totalVertices != null) {
  38547. this._totalVertices = totalVertices;
  38548. }
  38549. else {
  38550. if (data != null) {
  38551. this._totalVertices = data.length / (buffer.byteStride / 4);
  38552. }
  38553. }
  38554. this._updateExtend(data);
  38555. this._resetPointsArrayCache();
  38556. var meshes = this._meshes;
  38557. var numOfMeshes = meshes.length;
  38558. for (var index = 0; index < numOfMeshes; index++) {
  38559. var mesh = meshes[index];
  38560. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38561. mesh._createGlobalSubMesh(false);
  38562. mesh.computeWorldMatrix(true);
  38563. }
  38564. }
  38565. this.notifyUpdate(kind);
  38566. if (this._vertexArrayObjects) {
  38567. this._disposeVertexArrayObjects();
  38568. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38569. }
  38570. };
  38571. /**
  38572. * Update a specific vertex buffer
  38573. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38574. * It will do nothing if the buffer is not updatable
  38575. * @param kind defines the data kind (Position, normal, etc...)
  38576. * @param data defines the data to use
  38577. * @param offset defines the offset in the target buffer where to store the data
  38578. * @param useBytes set to true if the offset is in bytes
  38579. */
  38580. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38581. if (useBytes === void 0) { useBytes = false; }
  38582. var vertexBuffer = this.getVertexBuffer(kind);
  38583. if (!vertexBuffer) {
  38584. return;
  38585. }
  38586. vertexBuffer.updateDirectly(data, offset, useBytes);
  38587. this.notifyUpdate(kind);
  38588. };
  38589. /**
  38590. * Update a specific vertex buffer
  38591. * This function will create a new buffer if the current one is not updatable
  38592. * @param kind defines the data kind (Position, normal, etc...)
  38593. * @param data defines the data to use
  38594. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38595. */
  38596. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38597. if (updateExtends === void 0) { updateExtends = false; }
  38598. var vertexBuffer = this.getVertexBuffer(kind);
  38599. if (!vertexBuffer) {
  38600. return;
  38601. }
  38602. vertexBuffer.update(data);
  38603. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38604. this._updateBoundingInfo(updateExtends, data);
  38605. }
  38606. this.notifyUpdate(kind);
  38607. };
  38608. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38609. if (updateExtends) {
  38610. this._updateExtend(data);
  38611. }
  38612. var meshes = this._meshes;
  38613. var numOfMeshes = meshes.length;
  38614. this._resetPointsArrayCache();
  38615. for (var index = 0; index < numOfMeshes; index++) {
  38616. var mesh = meshes[index];
  38617. if (updateExtends) {
  38618. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38619. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38620. var subMesh = mesh.subMeshes[subIndex];
  38621. subMesh.refreshBoundingInfo();
  38622. }
  38623. }
  38624. }
  38625. };
  38626. /** @hidden */
  38627. Geometry.prototype._bind = function (effect, indexToBind) {
  38628. if (!effect) {
  38629. return;
  38630. }
  38631. if (indexToBind === undefined) {
  38632. indexToBind = this._indexBuffer;
  38633. }
  38634. var vbs = this.getVertexBuffers();
  38635. if (!vbs) {
  38636. return;
  38637. }
  38638. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38639. this._engine.bindBuffers(vbs, indexToBind, effect);
  38640. return;
  38641. }
  38642. // Using VAO
  38643. if (!this._vertexArrayObjects[effect.key]) {
  38644. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38645. }
  38646. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38647. };
  38648. /**
  38649. * Gets total number of vertices
  38650. * @returns the total number of vertices
  38651. */
  38652. Geometry.prototype.getTotalVertices = function () {
  38653. if (!this.isReady()) {
  38654. return 0;
  38655. }
  38656. return this._totalVertices;
  38657. };
  38658. /**
  38659. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38660. * @param kind defines the data kind (Position, normal, etc...)
  38661. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38662. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38663. * @returns a float array containing vertex data
  38664. */
  38665. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38666. var vertexBuffer = this.getVertexBuffer(kind);
  38667. if (!vertexBuffer) {
  38668. return null;
  38669. }
  38670. var data = vertexBuffer.getData();
  38671. if (!data) {
  38672. return null;
  38673. }
  38674. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38675. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38676. var count = this._totalVertices * defaultStride;
  38677. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38678. var copy_1 = new Array(count);
  38679. vertexBuffer.forEach(count, function (value, index) {
  38680. copy_1[index] = value;
  38681. });
  38682. return copy_1;
  38683. }
  38684. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38685. if (data instanceof Array) {
  38686. var offset = vertexBuffer.byteOffset / 4;
  38687. return BABYLON.Tools.Slice(data, offset, offset + count);
  38688. }
  38689. else if (data instanceof ArrayBuffer) {
  38690. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38691. }
  38692. else {
  38693. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38694. }
  38695. }
  38696. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38697. return BABYLON.Tools.Slice(data);
  38698. }
  38699. return data;
  38700. };
  38701. /**
  38702. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38703. * @param kind defines the data kind (Position, normal, etc...)
  38704. * @returns true if the vertex buffer with the specified kind is updatable
  38705. */
  38706. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38707. var vb = this._vertexBuffers[kind];
  38708. if (!vb) {
  38709. return false;
  38710. }
  38711. return vb.isUpdatable();
  38712. };
  38713. /**
  38714. * Gets a specific vertex buffer
  38715. * @param kind defines the data kind (Position, normal, etc...)
  38716. * @returns a {BABYLON.VertexBuffer}
  38717. */
  38718. Geometry.prototype.getVertexBuffer = function (kind) {
  38719. if (!this.isReady()) {
  38720. return null;
  38721. }
  38722. return this._vertexBuffers[kind];
  38723. };
  38724. /**
  38725. * Returns all vertex buffers
  38726. * @return an object holding all vertex buffers indexed by kind
  38727. */
  38728. Geometry.prototype.getVertexBuffers = function () {
  38729. if (!this.isReady()) {
  38730. return null;
  38731. }
  38732. return this._vertexBuffers;
  38733. };
  38734. /**
  38735. * Gets a boolean indicating if specific vertex buffer is present
  38736. * @param kind defines the data kind (Position, normal, etc...)
  38737. * @returns true if data is present
  38738. */
  38739. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38740. if (!this._vertexBuffers) {
  38741. if (this._delayInfo) {
  38742. return this._delayInfo.indexOf(kind) !== -1;
  38743. }
  38744. return false;
  38745. }
  38746. return this._vertexBuffers[kind] !== undefined;
  38747. };
  38748. /**
  38749. * Gets a list of all attached data kinds (Position, normal, etc...)
  38750. * @returns a list of string containing all kinds
  38751. */
  38752. Geometry.prototype.getVerticesDataKinds = function () {
  38753. var result = [];
  38754. var kind;
  38755. if (!this._vertexBuffers && this._delayInfo) {
  38756. for (kind in this._delayInfo) {
  38757. result.push(kind);
  38758. }
  38759. }
  38760. else {
  38761. for (kind in this._vertexBuffers) {
  38762. result.push(kind);
  38763. }
  38764. }
  38765. return result;
  38766. };
  38767. /**
  38768. * Update index buffer
  38769. * @param indices defines the indices to store in the index buffer
  38770. * @param offset defines the offset in the target buffer where to store the data
  38771. */
  38772. Geometry.prototype.updateIndices = function (indices, offset) {
  38773. if (!this._indexBuffer) {
  38774. return;
  38775. }
  38776. if (!this._indexBufferIsUpdatable) {
  38777. this.setIndices(indices, null, true);
  38778. }
  38779. else {
  38780. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38781. }
  38782. };
  38783. /**
  38784. * Creates a new index buffer
  38785. * @param indices defines the indices to store in the index buffer
  38786. * @param totalVertices defines the total number of vertices (could be null)
  38787. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38788. */
  38789. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38790. if (totalVertices === void 0) { totalVertices = null; }
  38791. if (updatable === void 0) { updatable = false; }
  38792. if (this._indexBuffer) {
  38793. this._engine._releaseBuffer(this._indexBuffer);
  38794. }
  38795. this._disposeVertexArrayObjects();
  38796. this._indices = indices;
  38797. this._indexBufferIsUpdatable = updatable;
  38798. if (this._meshes.length !== 0 && this._indices) {
  38799. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38800. }
  38801. if (totalVertices != undefined) { // including null and undefined
  38802. this._totalVertices = totalVertices;
  38803. }
  38804. var meshes = this._meshes;
  38805. var numOfMeshes = meshes.length;
  38806. for (var index = 0; index < numOfMeshes; index++) {
  38807. meshes[index]._createGlobalSubMesh(true);
  38808. }
  38809. this.notifyUpdate();
  38810. };
  38811. /**
  38812. * Return the total number of indices
  38813. * @returns the total number of indices
  38814. */
  38815. Geometry.prototype.getTotalIndices = function () {
  38816. if (!this.isReady()) {
  38817. return 0;
  38818. }
  38819. return this._indices.length;
  38820. };
  38821. /**
  38822. * Gets the index buffer array
  38823. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38824. * @returns the index buffer array
  38825. */
  38826. Geometry.prototype.getIndices = function (copyWhenShared) {
  38827. if (!this.isReady()) {
  38828. return null;
  38829. }
  38830. var orig = this._indices;
  38831. if (!copyWhenShared || this._meshes.length === 1) {
  38832. return orig;
  38833. }
  38834. else {
  38835. var len = orig.length;
  38836. var copy = [];
  38837. for (var i = 0; i < len; i++) {
  38838. copy.push(orig[i]);
  38839. }
  38840. return copy;
  38841. }
  38842. };
  38843. /**
  38844. * Gets the index buffer
  38845. * @return the index buffer
  38846. */
  38847. Geometry.prototype.getIndexBuffer = function () {
  38848. if (!this.isReady()) {
  38849. return null;
  38850. }
  38851. return this._indexBuffer;
  38852. };
  38853. /** @hidden */
  38854. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38855. if (effect === void 0) { effect = null; }
  38856. if (!effect || !this._vertexArrayObjects) {
  38857. return;
  38858. }
  38859. if (this._vertexArrayObjects[effect.key]) {
  38860. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38861. delete this._vertexArrayObjects[effect.key];
  38862. }
  38863. };
  38864. /**
  38865. * Release the associated resources for a specific mesh
  38866. * @param mesh defines the source mesh
  38867. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38868. */
  38869. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38870. var meshes = this._meshes;
  38871. var index = meshes.indexOf(mesh);
  38872. if (index === -1) {
  38873. return;
  38874. }
  38875. meshes.splice(index, 1);
  38876. mesh._geometry = null;
  38877. if (meshes.length === 0 && shouldDispose) {
  38878. this.dispose();
  38879. }
  38880. };
  38881. /**
  38882. * Apply current geometry to a given mesh
  38883. * @param mesh defines the mesh to apply geometry to
  38884. */
  38885. Geometry.prototype.applyToMesh = function (mesh) {
  38886. if (mesh._geometry === this) {
  38887. return;
  38888. }
  38889. var previousGeometry = mesh._geometry;
  38890. if (previousGeometry) {
  38891. previousGeometry.releaseForMesh(mesh);
  38892. }
  38893. var meshes = this._meshes;
  38894. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38895. mesh._geometry = this;
  38896. this._scene.pushGeometry(this);
  38897. meshes.push(mesh);
  38898. if (this.isReady()) {
  38899. this._applyToMesh(mesh);
  38900. }
  38901. else {
  38902. mesh._boundingInfo = this._boundingInfo;
  38903. }
  38904. };
  38905. Geometry.prototype._updateExtend = function (data) {
  38906. if (data === void 0) { data = null; }
  38907. if (!data) {
  38908. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38909. }
  38910. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38911. };
  38912. Geometry.prototype._applyToMesh = function (mesh) {
  38913. var numOfMeshes = this._meshes.length;
  38914. // vertexBuffers
  38915. for (var kind in this._vertexBuffers) {
  38916. if (numOfMeshes === 1) {
  38917. this._vertexBuffers[kind].create();
  38918. }
  38919. var buffer = this._vertexBuffers[kind].getBuffer();
  38920. if (buffer)
  38921. buffer.references = numOfMeshes;
  38922. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38923. if (!this._extend) {
  38924. this._updateExtend();
  38925. }
  38926. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38927. mesh._createGlobalSubMesh(false);
  38928. //bounding info was just created again, world matrix should be applied again.
  38929. mesh._updateBoundingInfo();
  38930. }
  38931. }
  38932. // indexBuffer
  38933. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38934. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38935. }
  38936. if (this._indexBuffer) {
  38937. this._indexBuffer.references = numOfMeshes;
  38938. }
  38939. };
  38940. Geometry.prototype.notifyUpdate = function (kind) {
  38941. if (this.onGeometryUpdated) {
  38942. this.onGeometryUpdated(this, kind);
  38943. }
  38944. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38945. var mesh = _a[_i];
  38946. mesh._markSubMeshesAsAttributesDirty();
  38947. }
  38948. };
  38949. /**
  38950. * Load the geometry if it was flagged as delay loaded
  38951. * @param scene defines the hosting scene
  38952. * @param onLoaded defines a callback called when the geometry is loaded
  38953. */
  38954. Geometry.prototype.load = function (scene, onLoaded) {
  38955. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38956. return;
  38957. }
  38958. if (this.isReady()) {
  38959. if (onLoaded) {
  38960. onLoaded();
  38961. }
  38962. return;
  38963. }
  38964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38965. this._queueLoad(scene, onLoaded);
  38966. };
  38967. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38968. var _this = this;
  38969. if (!this.delayLoadingFile) {
  38970. return;
  38971. }
  38972. scene._addPendingData(this);
  38973. scene._loadFile(this.delayLoadingFile, function (data) {
  38974. if (!_this._delayLoadingFunction) {
  38975. return;
  38976. }
  38977. _this._delayLoadingFunction(JSON.parse(data), _this);
  38978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38979. _this._delayInfo = [];
  38980. scene._removePendingData(_this);
  38981. var meshes = _this._meshes;
  38982. var numOfMeshes = meshes.length;
  38983. for (var index = 0; index < numOfMeshes; index++) {
  38984. _this._applyToMesh(meshes[index]);
  38985. }
  38986. if (onLoaded) {
  38987. onLoaded();
  38988. }
  38989. }, undefined, true);
  38990. };
  38991. /**
  38992. * Invert the geometry to move from a right handed system to a left handed one.
  38993. */
  38994. Geometry.prototype.toLeftHanded = function () {
  38995. // Flip faces
  38996. var tIndices = this.getIndices(false);
  38997. if (tIndices != null && tIndices.length > 0) {
  38998. for (var i = 0; i < tIndices.length; i += 3) {
  38999. var tTemp = tIndices[i + 0];
  39000. tIndices[i + 0] = tIndices[i + 2];
  39001. tIndices[i + 2] = tTemp;
  39002. }
  39003. this.setIndices(tIndices);
  39004. }
  39005. // Negate position.z
  39006. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39007. if (tPositions != null && tPositions.length > 0) {
  39008. for (var i = 0; i < tPositions.length; i += 3) {
  39009. tPositions[i + 2] = -tPositions[i + 2];
  39010. }
  39011. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39012. }
  39013. // Negate normal.z
  39014. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39015. if (tNormals != null && tNormals.length > 0) {
  39016. for (var i = 0; i < tNormals.length; i += 3) {
  39017. tNormals[i + 2] = -tNormals[i + 2];
  39018. }
  39019. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39020. }
  39021. };
  39022. // Cache
  39023. /** @hidden */
  39024. Geometry.prototype._resetPointsArrayCache = function () {
  39025. this._positions = null;
  39026. };
  39027. /** @hidden */
  39028. Geometry.prototype._generatePointsArray = function () {
  39029. if (this._positions)
  39030. return true;
  39031. this._positions = [];
  39032. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39033. if (!data) {
  39034. return false;
  39035. }
  39036. for (var index = 0; index < data.length; index += 3) {
  39037. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39038. }
  39039. return true;
  39040. };
  39041. /**
  39042. * Gets a value indicating if the geometry is disposed
  39043. * @returns true if the geometry was disposed
  39044. */
  39045. Geometry.prototype.isDisposed = function () {
  39046. return this._isDisposed;
  39047. };
  39048. Geometry.prototype._disposeVertexArrayObjects = function () {
  39049. if (this._vertexArrayObjects) {
  39050. for (var kind in this._vertexArrayObjects) {
  39051. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39052. }
  39053. this._vertexArrayObjects = {};
  39054. }
  39055. };
  39056. /**
  39057. * Free all associated resources
  39058. */
  39059. Geometry.prototype.dispose = function () {
  39060. var meshes = this._meshes;
  39061. var numOfMeshes = meshes.length;
  39062. var index;
  39063. for (index = 0; index < numOfMeshes; index++) {
  39064. this.releaseForMesh(meshes[index]);
  39065. }
  39066. this._meshes = [];
  39067. this._disposeVertexArrayObjects();
  39068. for (var kind in this._vertexBuffers) {
  39069. this._vertexBuffers[kind].dispose();
  39070. }
  39071. this._vertexBuffers = {};
  39072. this._totalVertices = 0;
  39073. if (this._indexBuffer) {
  39074. this._engine._releaseBuffer(this._indexBuffer);
  39075. }
  39076. this._indexBuffer = null;
  39077. this._indices = [];
  39078. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39079. this.delayLoadingFile = null;
  39080. this._delayLoadingFunction = null;
  39081. this._delayInfo = [];
  39082. this._boundingInfo = null;
  39083. this._scene.removeGeometry(this);
  39084. this._isDisposed = true;
  39085. };
  39086. /**
  39087. * Clone the current geometry into a new geometry
  39088. * @param id defines the unique ID of the new geometry
  39089. * @returns a new geometry object
  39090. */
  39091. Geometry.prototype.copy = function (id) {
  39092. var vertexData = new BABYLON.VertexData();
  39093. vertexData.indices = [];
  39094. var indices = this.getIndices();
  39095. if (indices) {
  39096. for (var index = 0; index < indices.length; index++) {
  39097. vertexData.indices.push(indices[index]);
  39098. }
  39099. }
  39100. var updatable = false;
  39101. var stopChecking = false;
  39102. var kind;
  39103. for (kind in this._vertexBuffers) {
  39104. // using slice() to make a copy of the array and not just reference it
  39105. var data = this.getVerticesData(kind);
  39106. if (data instanceof Float32Array) {
  39107. vertexData.set(new Float32Array(data), kind);
  39108. }
  39109. else {
  39110. vertexData.set(data.slice(0), kind);
  39111. }
  39112. if (!stopChecking) {
  39113. var vb = this.getVertexBuffer(kind);
  39114. if (vb) {
  39115. updatable = vb.isUpdatable();
  39116. stopChecking = !updatable;
  39117. }
  39118. }
  39119. }
  39120. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39121. geometry.delayLoadState = this.delayLoadState;
  39122. geometry.delayLoadingFile = this.delayLoadingFile;
  39123. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39124. for (kind in this._delayInfo) {
  39125. geometry._delayInfo = geometry._delayInfo || [];
  39126. geometry._delayInfo.push(kind);
  39127. }
  39128. // Bounding info
  39129. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39130. return geometry;
  39131. };
  39132. /**
  39133. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39134. * @return a JSON representation of the current geometry data (without the vertices data)
  39135. */
  39136. Geometry.prototype.serialize = function () {
  39137. var serializationObject = {};
  39138. serializationObject.id = this.id;
  39139. serializationObject.updatable = this._updatable;
  39140. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39141. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39142. }
  39143. return serializationObject;
  39144. };
  39145. Geometry.prototype.toNumberArray = function (origin) {
  39146. if (Array.isArray(origin)) {
  39147. return origin;
  39148. }
  39149. else {
  39150. return Array.prototype.slice.call(origin);
  39151. }
  39152. };
  39153. /**
  39154. * Serialize all vertices data into a JSON oject
  39155. * @returns a JSON representation of the current geometry data
  39156. */
  39157. Geometry.prototype.serializeVerticeData = function () {
  39158. var serializationObject = this.serialize();
  39159. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39160. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39161. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39162. serializationObject.positions._updatable = true;
  39163. }
  39164. }
  39165. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39166. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39167. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39168. serializationObject.normals._updatable = true;
  39169. }
  39170. }
  39171. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39172. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39173. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39174. serializationObject.tangets._updatable = true;
  39175. }
  39176. }
  39177. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39178. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39179. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39180. serializationObject.uvs._updatable = true;
  39181. }
  39182. }
  39183. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39184. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39185. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39186. serializationObject.uv2s._updatable = true;
  39187. }
  39188. }
  39189. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39190. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39191. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39192. serializationObject.uv3s._updatable = true;
  39193. }
  39194. }
  39195. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39196. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39197. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39198. serializationObject.uv4s._updatable = true;
  39199. }
  39200. }
  39201. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39202. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39203. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39204. serializationObject.uv5s._updatable = true;
  39205. }
  39206. }
  39207. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39208. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39209. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39210. serializationObject.uv6s._updatable = true;
  39211. }
  39212. }
  39213. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39214. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39215. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39216. serializationObject.colors._updatable = true;
  39217. }
  39218. }
  39219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39220. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39221. serializationObject.matricesIndices._isExpanded = true;
  39222. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39223. serializationObject.matricesIndices._updatable = true;
  39224. }
  39225. }
  39226. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39227. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39228. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39229. serializationObject.matricesWeights._updatable = true;
  39230. }
  39231. }
  39232. serializationObject.indices = this.toNumberArray(this.getIndices());
  39233. return serializationObject;
  39234. };
  39235. // Statics
  39236. /**
  39237. * Extracts a clone of a mesh geometry
  39238. * @param mesh defines the source mesh
  39239. * @param id defines the unique ID of the new geometry object
  39240. * @returns the new geometry object
  39241. */
  39242. Geometry.ExtractFromMesh = function (mesh, id) {
  39243. var geometry = mesh._geometry;
  39244. if (!geometry) {
  39245. return null;
  39246. }
  39247. return geometry.copy(id);
  39248. };
  39249. /**
  39250. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39251. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39252. * Be aware Math.random() could cause collisions, but:
  39253. * "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"
  39254. * @returns a string containing a new GUID
  39255. */
  39256. Geometry.RandomId = function () {
  39257. return BABYLON.Tools.RandomId();
  39258. };
  39259. /** @hidden */
  39260. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39261. var scene = mesh.getScene();
  39262. // Geometry
  39263. var geometryId = parsedGeometry.geometryId;
  39264. if (geometryId) {
  39265. var geometry = scene.getGeometryByID(geometryId);
  39266. if (geometry) {
  39267. geometry.applyToMesh(mesh);
  39268. }
  39269. }
  39270. else if (parsedGeometry instanceof ArrayBuffer) {
  39271. var binaryInfo = mesh._binaryInfo;
  39272. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39273. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39274. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39275. }
  39276. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39277. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39278. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39279. }
  39280. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39281. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39282. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39283. }
  39284. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39285. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39286. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39287. }
  39288. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39289. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39290. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39291. }
  39292. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39293. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39294. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39295. }
  39296. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39297. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39298. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39299. }
  39300. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39301. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39302. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39303. }
  39304. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39305. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39306. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39307. }
  39308. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39309. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39310. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39311. }
  39312. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39313. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39314. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39315. }
  39316. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39317. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39318. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39319. }
  39320. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39321. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39322. mesh.setIndices(indicesData, null);
  39323. }
  39324. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39325. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39326. mesh.subMeshes = [];
  39327. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39328. var materialIndex = subMeshesData[(i * 5) + 0];
  39329. var verticesStart = subMeshesData[(i * 5) + 1];
  39330. var verticesCount = subMeshesData[(i * 5) + 2];
  39331. var indexStart = subMeshesData[(i * 5) + 3];
  39332. var indexCount = subMeshesData[(i * 5) + 4];
  39333. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39334. }
  39335. }
  39336. }
  39337. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39338. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39339. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39340. if (parsedGeometry.tangents) {
  39341. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39342. }
  39343. if (parsedGeometry.uvs) {
  39344. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39345. }
  39346. if (parsedGeometry.uvs2) {
  39347. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39348. }
  39349. if (parsedGeometry.uvs3) {
  39350. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39351. }
  39352. if (parsedGeometry.uvs4) {
  39353. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39354. }
  39355. if (parsedGeometry.uvs5) {
  39356. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39357. }
  39358. if (parsedGeometry.uvs6) {
  39359. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39360. }
  39361. if (parsedGeometry.colors) {
  39362. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39363. }
  39364. if (parsedGeometry.matricesIndices) {
  39365. if (!parsedGeometry.matricesIndices._isExpanded) {
  39366. var floatIndices = [];
  39367. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39368. var matricesIndex = parsedGeometry.matricesIndices[i];
  39369. floatIndices.push(matricesIndex & 0x000000FF);
  39370. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39371. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39372. floatIndices.push(matricesIndex >> 24);
  39373. }
  39374. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39375. }
  39376. else {
  39377. delete parsedGeometry.matricesIndices._isExpanded;
  39378. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39379. }
  39380. }
  39381. if (parsedGeometry.matricesIndicesExtra) {
  39382. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39383. var floatIndices = [];
  39384. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39385. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39386. floatIndices.push(matricesIndex & 0x000000FF);
  39387. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39388. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39389. floatIndices.push(matricesIndex >> 24);
  39390. }
  39391. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39392. }
  39393. else {
  39394. delete parsedGeometry.matricesIndices._isExpanded;
  39395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39396. }
  39397. }
  39398. if (parsedGeometry.matricesWeights) {
  39399. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39400. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39401. }
  39402. if (parsedGeometry.matricesWeightsExtra) {
  39403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39404. }
  39405. mesh.setIndices(parsedGeometry.indices, null);
  39406. }
  39407. // SubMeshes
  39408. if (parsedGeometry.subMeshes) {
  39409. mesh.subMeshes = [];
  39410. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39411. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39412. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39413. }
  39414. }
  39415. // Flat shading
  39416. if (mesh._shouldGenerateFlatShading) {
  39417. mesh.convertToFlatShadedMesh();
  39418. delete mesh._shouldGenerateFlatShading;
  39419. }
  39420. // Update
  39421. mesh.computeWorldMatrix(true);
  39422. // Octree
  39423. var sceneOctree = scene.selectionOctree;
  39424. if (sceneOctree !== undefined && sceneOctree !== null) {
  39425. sceneOctree.addMesh(mesh);
  39426. }
  39427. };
  39428. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39429. var epsilon = 1e-3;
  39430. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39431. return;
  39432. }
  39433. var noInfluenceBoneIndex = 0.0;
  39434. if (parsedGeometry.skeletonId > -1) {
  39435. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39436. if (!skeleton) {
  39437. return;
  39438. }
  39439. noInfluenceBoneIndex = skeleton.bones.length;
  39440. }
  39441. else {
  39442. return;
  39443. }
  39444. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39445. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39446. var matricesWeights = parsedGeometry.matricesWeights;
  39447. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39448. var influencers = parsedGeometry.numBoneInfluencer;
  39449. var size = matricesWeights.length;
  39450. for (var i = 0; i < size; i += 4) {
  39451. var weight = 0.0;
  39452. var firstZeroWeight = -1;
  39453. for (var j = 0; j < 4; j++) {
  39454. var w = matricesWeights[i + j];
  39455. weight += w;
  39456. if (w < epsilon && firstZeroWeight < 0) {
  39457. firstZeroWeight = j;
  39458. }
  39459. }
  39460. if (matricesWeightsExtra) {
  39461. for (var j = 0; j < 4; j++) {
  39462. var w = matricesWeightsExtra[i + j];
  39463. weight += w;
  39464. if (w < epsilon && firstZeroWeight < 0) {
  39465. firstZeroWeight = j + 4;
  39466. }
  39467. }
  39468. }
  39469. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39470. firstZeroWeight = influencers - 1;
  39471. }
  39472. if (weight > epsilon) {
  39473. var mweight = 1.0 / weight;
  39474. for (var j = 0; j < 4; j++) {
  39475. matricesWeights[i + j] *= mweight;
  39476. }
  39477. if (matricesWeightsExtra) {
  39478. for (var j = 0; j < 4; j++) {
  39479. matricesWeightsExtra[i + j] *= mweight;
  39480. }
  39481. }
  39482. }
  39483. else {
  39484. if (firstZeroWeight >= 4) {
  39485. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39486. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39487. }
  39488. else {
  39489. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39490. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39491. }
  39492. }
  39493. }
  39494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39495. if (parsedGeometry.matricesWeightsExtra) {
  39496. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39497. }
  39498. };
  39499. /**
  39500. * Create a new geometry from persisted data (Using .babylon file format)
  39501. * @param parsedVertexData defines the persisted data
  39502. * @param scene defines the hosting scene
  39503. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39504. * @returns the new geometry object
  39505. */
  39506. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39507. if (scene.getGeometryByID(parsedVertexData.id)) {
  39508. return null; // null since geometry could be something else than a box...
  39509. }
  39510. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39511. if (BABYLON.Tags) {
  39512. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39513. }
  39514. if (parsedVertexData.delayLoadingFile) {
  39515. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39516. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39517. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39518. geometry._delayInfo = [];
  39519. if (parsedVertexData.hasUVs) {
  39520. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39521. }
  39522. if (parsedVertexData.hasUVs2) {
  39523. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39524. }
  39525. if (parsedVertexData.hasUVs3) {
  39526. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39527. }
  39528. if (parsedVertexData.hasUVs4) {
  39529. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39530. }
  39531. if (parsedVertexData.hasUVs5) {
  39532. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39533. }
  39534. if (parsedVertexData.hasUVs6) {
  39535. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39536. }
  39537. if (parsedVertexData.hasColors) {
  39538. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39539. }
  39540. if (parsedVertexData.hasMatricesIndices) {
  39541. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39542. }
  39543. if (parsedVertexData.hasMatricesWeights) {
  39544. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39545. }
  39546. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39547. }
  39548. else {
  39549. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39550. }
  39551. scene.pushGeometry(geometry, true);
  39552. return geometry;
  39553. };
  39554. return Geometry;
  39555. }());
  39556. BABYLON.Geometry = Geometry;
  39557. // Primitives
  39558. /// Abstract class
  39559. /**
  39560. * Abstract class used to provide common services for all typed geometries
  39561. * @hidden
  39562. */
  39563. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39564. __extends(_PrimitiveGeometry, _super);
  39565. /**
  39566. * Creates a new typed geometry
  39567. * @param id defines the unique ID of the geometry
  39568. * @param scene defines the hosting scene
  39569. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39570. * @param mesh defines the hosting mesh (can be null)
  39571. */
  39572. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39573. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39574. if (mesh === void 0) { mesh = null; }
  39575. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39576. _this._canBeRegenerated = _canBeRegenerated;
  39577. _this._beingRegenerated = true;
  39578. _this.regenerate();
  39579. _this._beingRegenerated = false;
  39580. return _this;
  39581. }
  39582. /**
  39583. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39584. * @returns true if the geometry can be regenerated
  39585. */
  39586. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39587. return this._canBeRegenerated;
  39588. };
  39589. /**
  39590. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39591. */
  39592. _PrimitiveGeometry.prototype.regenerate = function () {
  39593. if (!this._canBeRegenerated) {
  39594. return;
  39595. }
  39596. this._beingRegenerated = true;
  39597. this.setAllVerticesData(this._regenerateVertexData(), false);
  39598. this._beingRegenerated = false;
  39599. };
  39600. /**
  39601. * Clone the geometry
  39602. * @param id defines the unique ID of the new geometry
  39603. * @returns the new geometry
  39604. */
  39605. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39606. return _super.prototype.copy.call(this, id);
  39607. };
  39608. // overrides
  39609. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39610. if (!this._beingRegenerated) {
  39611. return;
  39612. }
  39613. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39614. };
  39615. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39616. if (!this._beingRegenerated) {
  39617. return;
  39618. }
  39619. _super.prototype.setVerticesData.call(this, kind, data, false);
  39620. };
  39621. // to override
  39622. /** @hidden */
  39623. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39624. throw new Error("Abstract method");
  39625. };
  39626. _PrimitiveGeometry.prototype.copy = function (id) {
  39627. throw new Error("Must be overriden in sub-classes.");
  39628. };
  39629. _PrimitiveGeometry.prototype.serialize = function () {
  39630. var serializationObject = _super.prototype.serialize.call(this);
  39631. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39632. return serializationObject;
  39633. };
  39634. return _PrimitiveGeometry;
  39635. }(Geometry));
  39636. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39637. /**
  39638. * Creates a ribbon geometry
  39639. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39640. */
  39641. var RibbonGeometry = /** @class */ (function (_super) {
  39642. __extends(RibbonGeometry, _super);
  39643. /**
  39644. * Creates a ribbon geometry
  39645. * @param id defines the unique ID of the geometry
  39646. * @param scene defines the hosting scene
  39647. * @param pathArray defines the array of paths to use
  39648. * @param closeArray defines if the last path and the first path must be joined
  39649. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39650. * @param offset defines the offset between points
  39651. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39652. * @param mesh defines the hosting mesh (can be null)
  39653. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39654. */
  39655. function RibbonGeometry(id, scene,
  39656. /**
  39657. * Defines the array of paths to use
  39658. */
  39659. pathArray,
  39660. /**
  39661. * Defines if the last and first points of each path in your pathArray must be joined
  39662. */
  39663. closeArray,
  39664. /**
  39665. * Defines if the last and first points of each path in your pathArray must be joined
  39666. */
  39667. closePath,
  39668. /**
  39669. * Defines the offset between points
  39670. */
  39671. offset, canBeRegenerated, mesh,
  39672. /**
  39673. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39674. */
  39675. side) {
  39676. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39677. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39678. _this.pathArray = pathArray;
  39679. _this.closeArray = closeArray;
  39680. _this.closePath = closePath;
  39681. _this.offset = offset;
  39682. _this.side = side;
  39683. return _this;
  39684. }
  39685. /** @hidden */
  39686. RibbonGeometry.prototype._regenerateVertexData = function () {
  39687. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39688. };
  39689. RibbonGeometry.prototype.copy = function (id) {
  39690. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39691. };
  39692. return RibbonGeometry;
  39693. }(_PrimitiveGeometry));
  39694. BABYLON.RibbonGeometry = RibbonGeometry;
  39695. /**
  39696. * Creates a box geometry
  39697. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39698. */
  39699. var BoxGeometry = /** @class */ (function (_super) {
  39700. __extends(BoxGeometry, _super);
  39701. /**
  39702. * Creates a box geometry
  39703. * @param id defines the unique ID of the geometry
  39704. * @param scene defines the hosting scene
  39705. * @param size defines the zise of the box (width, height and depth are the same)
  39706. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39707. * @param mesh defines the hosting mesh (can be null)
  39708. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39709. */
  39710. function BoxGeometry(id, scene,
  39711. /**
  39712. * Defines the zise of the box (width, height and depth are the same)
  39713. */
  39714. size, canBeRegenerated, mesh,
  39715. /**
  39716. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39717. */
  39718. side) {
  39719. if (mesh === void 0) { mesh = null; }
  39720. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39721. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39722. _this.size = size;
  39723. _this.side = side;
  39724. return _this;
  39725. }
  39726. BoxGeometry.prototype._regenerateVertexData = function () {
  39727. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39728. };
  39729. BoxGeometry.prototype.copy = function (id) {
  39730. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39731. };
  39732. BoxGeometry.prototype.serialize = function () {
  39733. var serializationObject = _super.prototype.serialize.call(this);
  39734. serializationObject.size = this.size;
  39735. return serializationObject;
  39736. };
  39737. BoxGeometry.Parse = function (parsedBox, scene) {
  39738. if (scene.getGeometryByID(parsedBox.id)) {
  39739. return null; // null since geometry could be something else than a box...
  39740. }
  39741. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39742. if (BABYLON.Tags) {
  39743. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39744. }
  39745. scene.pushGeometry(box, true);
  39746. return box;
  39747. };
  39748. return BoxGeometry;
  39749. }(_PrimitiveGeometry));
  39750. BABYLON.BoxGeometry = BoxGeometry;
  39751. /**
  39752. * Creates a sphere geometry
  39753. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39754. */
  39755. var SphereGeometry = /** @class */ (function (_super) {
  39756. __extends(SphereGeometry, _super);
  39757. /**
  39758. * Create a new sphere geometry
  39759. * @param id defines the unique ID of the geometry
  39760. * @param scene defines the hosting scene
  39761. * @param segments defines the number of segments to use to create the sphere
  39762. * @param diameter defines the diameter of the sphere
  39763. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39764. * @param mesh defines the hosting mesh (can be null)
  39765. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39766. */
  39767. function SphereGeometry(id, scene,
  39768. /**
  39769. * Defines the number of segments to use to create the sphere
  39770. */
  39771. segments,
  39772. /**
  39773. * Defines the diameter of the sphere
  39774. */
  39775. diameter, canBeRegenerated, mesh,
  39776. /**
  39777. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39778. */
  39779. side) {
  39780. if (mesh === void 0) { mesh = null; }
  39781. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39782. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39783. _this.segments = segments;
  39784. _this.diameter = diameter;
  39785. _this.side = side;
  39786. return _this;
  39787. }
  39788. SphereGeometry.prototype._regenerateVertexData = function () {
  39789. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39790. };
  39791. SphereGeometry.prototype.copy = function (id) {
  39792. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39793. };
  39794. SphereGeometry.prototype.serialize = function () {
  39795. var serializationObject = _super.prototype.serialize.call(this);
  39796. serializationObject.segments = this.segments;
  39797. serializationObject.diameter = this.diameter;
  39798. return serializationObject;
  39799. };
  39800. SphereGeometry.Parse = function (parsedSphere, scene) {
  39801. if (scene.getGeometryByID(parsedSphere.id)) {
  39802. return null; // null since geometry could be something else than a sphere...
  39803. }
  39804. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39805. if (BABYLON.Tags) {
  39806. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39807. }
  39808. scene.pushGeometry(sphere, true);
  39809. return sphere;
  39810. };
  39811. return SphereGeometry;
  39812. }(_PrimitiveGeometry));
  39813. BABYLON.SphereGeometry = SphereGeometry;
  39814. /**
  39815. * Creates a disc geometry
  39816. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39817. */
  39818. var DiscGeometry = /** @class */ (function (_super) {
  39819. __extends(DiscGeometry, _super);
  39820. /**
  39821. * Creates a new disc geometry
  39822. * @param id defines the unique ID of the geometry
  39823. * @param scene defines the hosting scene
  39824. * @param radius defines the radius of the disc
  39825. * @param tessellation defines the tesselation factor to apply to the disc
  39826. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39827. * @param mesh defines the hosting mesh (can be null)
  39828. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39829. */
  39830. function DiscGeometry(id, scene,
  39831. /**
  39832. * Defines the radius of the disc
  39833. */
  39834. radius,
  39835. /**
  39836. * Defines the tesselation factor to apply to the disc
  39837. */
  39838. tessellation, canBeRegenerated, mesh,
  39839. /**
  39840. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39841. */
  39842. side) {
  39843. if (mesh === void 0) { mesh = null; }
  39844. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39845. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39846. _this.radius = radius;
  39847. _this.tessellation = tessellation;
  39848. _this.side = side;
  39849. return _this;
  39850. }
  39851. DiscGeometry.prototype._regenerateVertexData = function () {
  39852. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39853. };
  39854. DiscGeometry.prototype.copy = function (id) {
  39855. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39856. };
  39857. return DiscGeometry;
  39858. }(_PrimitiveGeometry));
  39859. BABYLON.DiscGeometry = DiscGeometry;
  39860. /**
  39861. * Creates a new cylinder geometry
  39862. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39863. */
  39864. var CylinderGeometry = /** @class */ (function (_super) {
  39865. __extends(CylinderGeometry, _super);
  39866. /**
  39867. * Creates a new cylinder geometry
  39868. * @param id defines the unique ID of the geometry
  39869. * @param scene defines the hosting scene
  39870. * @param height defines the height of the cylinder
  39871. * @param diameterTop defines the diameter of the cylinder's top cap
  39872. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39873. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39874. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39875. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39876. * @param mesh defines the hosting mesh (can be null)
  39877. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39878. */
  39879. function CylinderGeometry(id, scene,
  39880. /**
  39881. * Defines the height of the cylinder
  39882. */
  39883. height,
  39884. /**
  39885. * Defines the diameter of the cylinder's top cap
  39886. */
  39887. diameterTop,
  39888. /**
  39889. * Defines the diameter of the cylinder's bottom cap
  39890. */
  39891. diameterBottom,
  39892. /**
  39893. * Defines the tessellation factor to apply to the cylinder
  39894. */
  39895. tessellation,
  39896. /**
  39897. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39898. */
  39899. subdivisions, canBeRegenerated, mesh,
  39900. /**
  39901. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39902. */
  39903. side) {
  39904. if (subdivisions === void 0) { subdivisions = 1; }
  39905. if (mesh === void 0) { mesh = null; }
  39906. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39907. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39908. _this.height = height;
  39909. _this.diameterTop = diameterTop;
  39910. _this.diameterBottom = diameterBottom;
  39911. _this.tessellation = tessellation;
  39912. _this.subdivisions = subdivisions;
  39913. _this.side = side;
  39914. return _this;
  39915. }
  39916. CylinderGeometry.prototype._regenerateVertexData = function () {
  39917. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39918. };
  39919. CylinderGeometry.prototype.copy = function (id) {
  39920. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39921. };
  39922. CylinderGeometry.prototype.serialize = function () {
  39923. var serializationObject = _super.prototype.serialize.call(this);
  39924. serializationObject.height = this.height;
  39925. serializationObject.diameterTop = this.diameterTop;
  39926. serializationObject.diameterBottom = this.diameterBottom;
  39927. serializationObject.tessellation = this.tessellation;
  39928. return serializationObject;
  39929. };
  39930. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39931. if (scene.getGeometryByID(parsedCylinder.id)) {
  39932. return null; // null since geometry could be something else than a cylinder...
  39933. }
  39934. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39935. if (BABYLON.Tags) {
  39936. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39937. }
  39938. scene.pushGeometry(cylinder, true);
  39939. return cylinder;
  39940. };
  39941. return CylinderGeometry;
  39942. }(_PrimitiveGeometry));
  39943. BABYLON.CylinderGeometry = CylinderGeometry;
  39944. /**
  39945. * Creates a new torus geometry
  39946. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39947. */
  39948. var TorusGeometry = /** @class */ (function (_super) {
  39949. __extends(TorusGeometry, _super);
  39950. /**
  39951. * Creates a new torus geometry
  39952. * @param id defines the unique ID of the geometry
  39953. * @param scene defines the hosting scene
  39954. * @param diameter defines the diameter of the torus
  39955. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39956. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39957. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39958. * @param mesh defines the hosting mesh (can be null)
  39959. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39960. */
  39961. function TorusGeometry(id, scene,
  39962. /**
  39963. * Defines the diameter of the torus
  39964. */
  39965. diameter,
  39966. /**
  39967. * Defines the thickness of the torus (ie. internal diameter)
  39968. */
  39969. thickness,
  39970. /**
  39971. * Defines the tesselation factor to apply to the torus
  39972. */
  39973. tessellation, canBeRegenerated, mesh,
  39974. /**
  39975. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39976. */
  39977. side) {
  39978. if (mesh === void 0) { mesh = null; }
  39979. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39980. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39981. _this.diameter = diameter;
  39982. _this.thickness = thickness;
  39983. _this.tessellation = tessellation;
  39984. _this.side = side;
  39985. return _this;
  39986. }
  39987. TorusGeometry.prototype._regenerateVertexData = function () {
  39988. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39989. };
  39990. TorusGeometry.prototype.copy = function (id) {
  39991. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39992. };
  39993. TorusGeometry.prototype.serialize = function () {
  39994. var serializationObject = _super.prototype.serialize.call(this);
  39995. serializationObject.diameter = this.diameter;
  39996. serializationObject.thickness = this.thickness;
  39997. serializationObject.tessellation = this.tessellation;
  39998. return serializationObject;
  39999. };
  40000. TorusGeometry.Parse = function (parsedTorus, scene) {
  40001. if (scene.getGeometryByID(parsedTorus.id)) {
  40002. return null; // null since geometry could be something else than a torus...
  40003. }
  40004. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40005. if (BABYLON.Tags) {
  40006. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40007. }
  40008. scene.pushGeometry(torus, true);
  40009. return torus;
  40010. };
  40011. return TorusGeometry;
  40012. }(_PrimitiveGeometry));
  40013. BABYLON.TorusGeometry = TorusGeometry;
  40014. /**
  40015. * Creates a new ground geometry
  40016. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40017. */
  40018. var GroundGeometry = /** @class */ (function (_super) {
  40019. __extends(GroundGeometry, _super);
  40020. /**
  40021. * Creates a new ground geometry
  40022. * @param id defines the unique ID of the geometry
  40023. * @param scene defines the hosting scene
  40024. * @param width defines the width of the ground
  40025. * @param height defines the height of the ground
  40026. * @param subdivisions defines the subdivisions to apply to the ground
  40027. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40028. * @param mesh defines the hosting mesh (can be null)
  40029. */
  40030. function GroundGeometry(id, scene,
  40031. /**
  40032. * Defines the width of the ground
  40033. */
  40034. width,
  40035. /**
  40036. * Defines the height of the ground
  40037. */
  40038. height,
  40039. /**
  40040. * Defines the subdivisions to apply to the ground
  40041. */
  40042. subdivisions, canBeRegenerated, mesh) {
  40043. if (mesh === void 0) { mesh = null; }
  40044. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40045. _this.width = width;
  40046. _this.height = height;
  40047. _this.subdivisions = subdivisions;
  40048. return _this;
  40049. }
  40050. GroundGeometry.prototype._regenerateVertexData = function () {
  40051. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40052. };
  40053. GroundGeometry.prototype.copy = function (id) {
  40054. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40055. };
  40056. GroundGeometry.prototype.serialize = function () {
  40057. var serializationObject = _super.prototype.serialize.call(this);
  40058. serializationObject.width = this.width;
  40059. serializationObject.height = this.height;
  40060. serializationObject.subdivisions = this.subdivisions;
  40061. return serializationObject;
  40062. };
  40063. GroundGeometry.Parse = function (parsedGround, scene) {
  40064. if (scene.getGeometryByID(parsedGround.id)) {
  40065. return null; // null since geometry could be something else than a ground...
  40066. }
  40067. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40068. if (BABYLON.Tags) {
  40069. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40070. }
  40071. scene.pushGeometry(ground, true);
  40072. return ground;
  40073. };
  40074. return GroundGeometry;
  40075. }(_PrimitiveGeometry));
  40076. BABYLON.GroundGeometry = GroundGeometry;
  40077. /**
  40078. * Creates a tiled ground geometry
  40079. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40080. */
  40081. var TiledGroundGeometry = /** @class */ (function (_super) {
  40082. __extends(TiledGroundGeometry, _super);
  40083. /**
  40084. * Creates a tiled ground geometry
  40085. * @param id defines the unique ID of the geometry
  40086. * @param scene defines the hosting scene
  40087. * @param xmin defines the minimum value on X axis
  40088. * @param zmin defines the minimum value on Z axis
  40089. * @param xmax defines the maximum value on X axis
  40090. * @param zmax defines the maximum value on Z axis
  40091. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40092. * @param precision defines the precision to use when computing the tiles
  40093. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40094. * @param mesh defines the hosting mesh (can be null)
  40095. */
  40096. function TiledGroundGeometry(id, scene,
  40097. /**
  40098. * Defines the minimum value on X axis
  40099. */
  40100. xmin,
  40101. /**
  40102. * Defines the minimum value on Z axis
  40103. */
  40104. zmin,
  40105. /**
  40106. * Defines the maximum value on X axis
  40107. */
  40108. xmax,
  40109. /**
  40110. * Defines the maximum value on Z axis
  40111. */
  40112. zmax,
  40113. /**
  40114. * Defines the subdivisions to apply to the ground
  40115. */
  40116. subdivisions,
  40117. /**
  40118. * Defines the precision to use when computing the tiles
  40119. */
  40120. precision, canBeRegenerated, mesh) {
  40121. if (mesh === void 0) { mesh = null; }
  40122. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40123. _this.xmin = xmin;
  40124. _this.zmin = zmin;
  40125. _this.xmax = xmax;
  40126. _this.zmax = zmax;
  40127. _this.subdivisions = subdivisions;
  40128. _this.precision = precision;
  40129. return _this;
  40130. }
  40131. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40132. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40133. };
  40134. TiledGroundGeometry.prototype.copy = function (id) {
  40135. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40136. };
  40137. return TiledGroundGeometry;
  40138. }(_PrimitiveGeometry));
  40139. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40140. /**
  40141. * Creates a plane geometry
  40142. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40143. */
  40144. var PlaneGeometry = /** @class */ (function (_super) {
  40145. __extends(PlaneGeometry, _super);
  40146. /**
  40147. * Creates a plane geometry
  40148. * @param id defines the unique ID of the geometry
  40149. * @param scene defines the hosting scene
  40150. * @param size defines the size of the plane (width === height)
  40151. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40152. * @param mesh defines the hosting mesh (can be null)
  40153. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40154. */
  40155. function PlaneGeometry(id, scene,
  40156. /**
  40157. * Defines the size of the plane (width === height)
  40158. */
  40159. size, canBeRegenerated, mesh,
  40160. /**
  40161. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40162. */
  40163. side) {
  40164. if (mesh === void 0) { mesh = null; }
  40165. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40166. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40167. _this.size = size;
  40168. _this.side = side;
  40169. return _this;
  40170. }
  40171. PlaneGeometry.prototype._regenerateVertexData = function () {
  40172. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40173. };
  40174. PlaneGeometry.prototype.copy = function (id) {
  40175. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40176. };
  40177. PlaneGeometry.prototype.serialize = function () {
  40178. var serializationObject = _super.prototype.serialize.call(this);
  40179. serializationObject.size = this.size;
  40180. return serializationObject;
  40181. };
  40182. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40183. if (scene.getGeometryByID(parsedPlane.id)) {
  40184. return null; // null since geometry could be something else than a ground...
  40185. }
  40186. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40187. if (BABYLON.Tags) {
  40188. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40189. }
  40190. scene.pushGeometry(plane, true);
  40191. return plane;
  40192. };
  40193. return PlaneGeometry;
  40194. }(_PrimitiveGeometry));
  40195. BABYLON.PlaneGeometry = PlaneGeometry;
  40196. /**
  40197. * Creates a torus knot geometry
  40198. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40199. */
  40200. var TorusKnotGeometry = /** @class */ (function (_super) {
  40201. __extends(TorusKnotGeometry, _super);
  40202. /**
  40203. * Creates a torus knot geometry
  40204. * @param id defines the unique ID of the geometry
  40205. * @param scene defines the hosting scene
  40206. * @param radius defines the radius of the torus knot
  40207. * @param tube defines the thickness of the torus knot tube
  40208. * @param radialSegments defines the number of radial segments
  40209. * @param tubularSegments defines the number of tubular segments
  40210. * @param p defines the first number of windings
  40211. * @param q defines the second number of windings
  40212. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40213. * @param mesh defines the hosting mesh (can be null)
  40214. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40215. */
  40216. function TorusKnotGeometry(id, scene,
  40217. /**
  40218. * Defines the radius of the torus knot
  40219. */
  40220. radius,
  40221. /**
  40222. * Defines the thickness of the torus knot tube
  40223. */
  40224. tube,
  40225. /**
  40226. * Defines the number of radial segments
  40227. */
  40228. radialSegments,
  40229. /**
  40230. * Defines the number of tubular segments
  40231. */
  40232. tubularSegments,
  40233. /**
  40234. * Defines the first number of windings
  40235. */
  40236. p,
  40237. /**
  40238. * Defines the second number of windings
  40239. */
  40240. q, canBeRegenerated, mesh,
  40241. /**
  40242. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40243. */
  40244. side) {
  40245. if (mesh === void 0) { mesh = null; }
  40246. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40247. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40248. _this.radius = radius;
  40249. _this.tube = tube;
  40250. _this.radialSegments = radialSegments;
  40251. _this.tubularSegments = tubularSegments;
  40252. _this.p = p;
  40253. _this.q = q;
  40254. _this.side = side;
  40255. return _this;
  40256. }
  40257. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40258. 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 });
  40259. };
  40260. TorusKnotGeometry.prototype.copy = function (id) {
  40261. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40262. };
  40263. TorusKnotGeometry.prototype.serialize = function () {
  40264. var serializationObject = _super.prototype.serialize.call(this);
  40265. serializationObject.radius = this.radius;
  40266. serializationObject.tube = this.tube;
  40267. serializationObject.radialSegments = this.radialSegments;
  40268. serializationObject.tubularSegments = this.tubularSegments;
  40269. serializationObject.p = this.p;
  40270. serializationObject.q = this.q;
  40271. return serializationObject;
  40272. };
  40273. ;
  40274. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40275. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40276. return null; // null since geometry could be something else than a ground...
  40277. }
  40278. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40279. if (BABYLON.Tags) {
  40280. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40281. }
  40282. scene.pushGeometry(torusKnot, true);
  40283. return torusKnot;
  40284. };
  40285. return TorusKnotGeometry;
  40286. }(_PrimitiveGeometry));
  40287. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40288. //}
  40289. })(BABYLON || (BABYLON = {}));
  40290. //# sourceMappingURL=babylon.geometry.js.map
  40291. var BABYLON;
  40292. (function (BABYLON) {
  40293. /**
  40294. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40295. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40296. */
  40297. var PostProcessManager = /** @class */ (function () {
  40298. /**
  40299. * Creates a new instance PostProcess
  40300. * @param scene The scene that the post process is associated with.
  40301. */
  40302. function PostProcessManager(scene) {
  40303. this._vertexBuffers = {};
  40304. this._scene = scene;
  40305. }
  40306. PostProcessManager.prototype._prepareBuffers = function () {
  40307. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40308. return;
  40309. }
  40310. // VBO
  40311. var vertices = [];
  40312. vertices.push(1, 1);
  40313. vertices.push(-1, 1);
  40314. vertices.push(-1, -1);
  40315. vertices.push(1, -1);
  40316. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40317. this._buildIndexBuffer();
  40318. };
  40319. PostProcessManager.prototype._buildIndexBuffer = function () {
  40320. // Indices
  40321. var indices = [];
  40322. indices.push(0);
  40323. indices.push(1);
  40324. indices.push(2);
  40325. indices.push(0);
  40326. indices.push(2);
  40327. indices.push(3);
  40328. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40329. };
  40330. /**
  40331. * Rebuilds the vertex buffers of the manager.
  40332. */
  40333. PostProcessManager.prototype._rebuild = function () {
  40334. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40335. if (!vb) {
  40336. return;
  40337. }
  40338. vb._rebuild();
  40339. this._buildIndexBuffer();
  40340. };
  40341. // Methods
  40342. /**
  40343. * Prepares a frame to be run through a post process.
  40344. * @param sourceTexture The input texture to the post procesess. (default: null)
  40345. * @param postProcesses An array of post processes to be run. (default: null)
  40346. * @returns True if the post processes were able to be run.
  40347. */
  40348. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40349. if (sourceTexture === void 0) { sourceTexture = null; }
  40350. if (postProcesses === void 0) { postProcesses = null; }
  40351. var camera = this._scene.activeCamera;
  40352. if (!camera) {
  40353. return false;
  40354. }
  40355. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40356. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40357. return false;
  40358. }
  40359. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40360. return true;
  40361. };
  40362. /**
  40363. * Manually render a set of post processes to a texture.
  40364. * @param postProcesses An array of post processes to be run.
  40365. * @param targetTexture The target texture to render to.
  40366. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40367. */
  40368. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40369. if (targetTexture === void 0) { targetTexture = null; }
  40370. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40371. var engine = this._scene.getEngine();
  40372. for (var index = 0; index < postProcesses.length; index++) {
  40373. if (index < postProcesses.length - 1) {
  40374. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40375. }
  40376. else {
  40377. if (targetTexture) {
  40378. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40379. }
  40380. else {
  40381. engine.restoreDefaultFramebuffer();
  40382. }
  40383. }
  40384. var pp = postProcesses[index];
  40385. var effect = pp.apply();
  40386. if (effect) {
  40387. pp.onBeforeRenderObservable.notifyObservers(effect);
  40388. // VBOs
  40389. this._prepareBuffers();
  40390. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40391. // Draw order
  40392. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40393. pp.onAfterRenderObservable.notifyObservers(effect);
  40394. }
  40395. }
  40396. // Restore depth buffer
  40397. engine.setDepthBuffer(true);
  40398. engine.setDepthWrite(true);
  40399. };
  40400. /**
  40401. * Finalize the result of the output of the postprocesses.
  40402. * @param doNotPresent If true the result will not be displayed to the screen.
  40403. * @param targetTexture The target texture to render to.
  40404. * @param faceIndex The index of the face to bind the target texture to.
  40405. * @param postProcesses The array of post processes to render.
  40406. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40407. */
  40408. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40409. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40410. var camera = this._scene.activeCamera;
  40411. if (!camera) {
  40412. return;
  40413. }
  40414. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40415. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40416. return;
  40417. }
  40418. var engine = this._scene.getEngine();
  40419. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40420. var pp = postProcesses[index];
  40421. if (index < len - 1) {
  40422. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40423. }
  40424. else {
  40425. if (targetTexture) {
  40426. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40427. pp._outputTexture = targetTexture;
  40428. }
  40429. else {
  40430. engine.restoreDefaultFramebuffer();
  40431. pp._outputTexture = null;
  40432. }
  40433. }
  40434. if (doNotPresent) {
  40435. break;
  40436. }
  40437. var effect = pp.apply();
  40438. if (effect) {
  40439. pp.onBeforeRenderObservable.notifyObservers(effect);
  40440. // VBOs
  40441. this._prepareBuffers();
  40442. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40443. // Draw order
  40444. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40445. pp.onAfterRenderObservable.notifyObservers(effect);
  40446. }
  40447. }
  40448. // Restore states
  40449. engine.setDepthBuffer(true);
  40450. engine.setDepthWrite(true);
  40451. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40452. };
  40453. /**
  40454. * Disposes of the post process manager.
  40455. */
  40456. PostProcessManager.prototype.dispose = function () {
  40457. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40458. if (buffer) {
  40459. buffer.dispose();
  40460. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40461. }
  40462. if (this._indexBuffer) {
  40463. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40464. this._indexBuffer = null;
  40465. }
  40466. };
  40467. return PostProcessManager;
  40468. }());
  40469. BABYLON.PostProcessManager = PostProcessManager;
  40470. })(BABYLON || (BABYLON = {}));
  40471. //# sourceMappingURL=babylon.postProcessManager.js.map
  40472. var BABYLON;
  40473. (function (BABYLON) {
  40474. /**
  40475. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40476. */
  40477. var PerformanceMonitor = /** @class */ (function () {
  40478. /**
  40479. * constructor
  40480. * @param frameSampleSize The number of samples required to saturate the sliding window
  40481. */
  40482. function PerformanceMonitor(frameSampleSize) {
  40483. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40484. this._enabled = true;
  40485. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40486. }
  40487. /**
  40488. * Samples current frame
  40489. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40490. */
  40491. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40492. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40493. if (!this._enabled)
  40494. return;
  40495. if (this._lastFrameTimeMs != null) {
  40496. var dt = timeMs - this._lastFrameTimeMs;
  40497. this._rollingFrameTime.add(dt);
  40498. }
  40499. this._lastFrameTimeMs = timeMs;
  40500. };
  40501. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40502. /**
  40503. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40504. * @return Average frame time in milliseconds
  40505. */
  40506. get: function () {
  40507. return this._rollingFrameTime.average;
  40508. },
  40509. enumerable: true,
  40510. configurable: true
  40511. });
  40512. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40513. /**
  40514. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40515. * @return Frame time variance in milliseconds squared
  40516. */
  40517. get: function () {
  40518. return this._rollingFrameTime.variance;
  40519. },
  40520. enumerable: true,
  40521. configurable: true
  40522. });
  40523. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40524. /**
  40525. * Returns the frame time of the most recent frame
  40526. * @return Frame time in milliseconds
  40527. */
  40528. get: function () {
  40529. return this._rollingFrameTime.history(0);
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40535. /**
  40536. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40537. * @return Framerate in frames per second
  40538. */
  40539. get: function () {
  40540. return 1000.0 / this._rollingFrameTime.average;
  40541. },
  40542. enumerable: true,
  40543. configurable: true
  40544. });
  40545. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40546. /**
  40547. * Returns the average framerate in frames per second using the most recent frame time
  40548. * @return Framerate in frames per second
  40549. */
  40550. get: function () {
  40551. var history = this._rollingFrameTime.history(0);
  40552. if (history === 0) {
  40553. return 0;
  40554. }
  40555. return 1000.0 / history;
  40556. },
  40557. enumerable: true,
  40558. configurable: true
  40559. });
  40560. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40561. /**
  40562. * Returns true if enough samples have been taken to completely fill the sliding window
  40563. * @return true if saturated
  40564. */
  40565. get: function () {
  40566. return this._rollingFrameTime.isSaturated();
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. /**
  40572. * Enables contributions to the sliding window sample set
  40573. */
  40574. PerformanceMonitor.prototype.enable = function () {
  40575. this._enabled = true;
  40576. };
  40577. /**
  40578. * Disables contributions to the sliding window sample set
  40579. * Samples will not be interpolated over the disabled period
  40580. */
  40581. PerformanceMonitor.prototype.disable = function () {
  40582. this._enabled = false;
  40583. //clear last sample to avoid interpolating over the disabled period when next enabled
  40584. this._lastFrameTimeMs = null;
  40585. };
  40586. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40587. /**
  40588. * Returns true if sampling is enabled
  40589. * @return true if enabled
  40590. */
  40591. get: function () {
  40592. return this._enabled;
  40593. },
  40594. enumerable: true,
  40595. configurable: true
  40596. });
  40597. /**
  40598. * Resets performance monitor
  40599. */
  40600. PerformanceMonitor.prototype.reset = function () {
  40601. //clear last sample to avoid interpolating over the disabled period when next enabled
  40602. this._lastFrameTimeMs = null;
  40603. //wipe record
  40604. this._rollingFrameTime.reset();
  40605. };
  40606. return PerformanceMonitor;
  40607. }());
  40608. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40609. /**
  40610. * RollingAverage
  40611. *
  40612. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40613. */
  40614. var RollingAverage = /** @class */ (function () {
  40615. /**
  40616. * constructor
  40617. * @param length The number of samples required to saturate the sliding window
  40618. */
  40619. function RollingAverage(length) {
  40620. this._samples = new Array(length);
  40621. this.reset();
  40622. }
  40623. /**
  40624. * Adds a sample to the sample set
  40625. * @param v The sample value
  40626. */
  40627. RollingAverage.prototype.add = function (v) {
  40628. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40629. var delta;
  40630. //we need to check if we've already wrapped round
  40631. if (this.isSaturated()) {
  40632. //remove bottom of stack from mean
  40633. var bottomValue = this._samples[this._pos];
  40634. delta = bottomValue - this.average;
  40635. this.average -= delta / (this._sampleCount - 1);
  40636. this._m2 -= delta * (bottomValue - this.average);
  40637. }
  40638. else {
  40639. this._sampleCount++;
  40640. }
  40641. //add new value to mean
  40642. delta = v - this.average;
  40643. this.average += delta / (this._sampleCount);
  40644. this._m2 += delta * (v - this.average);
  40645. //set the new variance
  40646. this.variance = this._m2 / (this._sampleCount - 1);
  40647. this._samples[this._pos] = v;
  40648. this._pos++;
  40649. this._pos %= this._samples.length; //positive wrap around
  40650. };
  40651. /**
  40652. * Returns previously added values or null if outside of history or outside the sliding window domain
  40653. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40654. * @return Value previously recorded with add() or null if outside of range
  40655. */
  40656. RollingAverage.prototype.history = function (i) {
  40657. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40658. return 0;
  40659. }
  40660. var i0 = this._wrapPosition(this._pos - 1.0);
  40661. return this._samples[this._wrapPosition(i0 - i)];
  40662. };
  40663. /**
  40664. * Returns true if enough samples have been taken to completely fill the sliding window
  40665. * @return true if sample-set saturated
  40666. */
  40667. RollingAverage.prototype.isSaturated = function () {
  40668. return this._sampleCount >= this._samples.length;
  40669. };
  40670. /**
  40671. * Resets the rolling average (equivalent to 0 samples taken so far)
  40672. */
  40673. RollingAverage.prototype.reset = function () {
  40674. this.average = 0;
  40675. this.variance = 0;
  40676. this._sampleCount = 0;
  40677. this._pos = 0;
  40678. this._m2 = 0;
  40679. };
  40680. /**
  40681. * Wraps a value around the sample range boundaries
  40682. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40683. * @return Wrapped position in sample range
  40684. */
  40685. RollingAverage.prototype._wrapPosition = function (i) {
  40686. var max = this._samples.length;
  40687. return ((i % max) + max) % max;
  40688. };
  40689. return RollingAverage;
  40690. }());
  40691. BABYLON.RollingAverage = RollingAverage;
  40692. })(BABYLON || (BABYLON = {}));
  40693. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40694. var BABYLON;
  40695. (function (BABYLON) {
  40696. /**
  40697. * This groups together the common properties used for image processing either in direct forward pass
  40698. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40699. * or not.
  40700. */
  40701. var ImageProcessingConfiguration = /** @class */ (function () {
  40702. function ImageProcessingConfiguration() {
  40703. /**
  40704. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40705. */
  40706. this.colorCurves = new BABYLON.ColorCurves();
  40707. this._colorCurvesEnabled = false;
  40708. this._colorGradingEnabled = false;
  40709. this._colorGradingWithGreenDepth = true;
  40710. this._colorGradingBGR = true;
  40711. this._exposure = 1.0;
  40712. this._toneMappingEnabled = false;
  40713. this._contrast = 1.0;
  40714. /**
  40715. * Vignette stretch size.
  40716. */
  40717. this.vignetteStretch = 0;
  40718. /**
  40719. * Vignette centre X Offset.
  40720. */
  40721. this.vignetteCentreX = 0;
  40722. /**
  40723. * Vignette centre Y Offset.
  40724. */
  40725. this.vignetteCentreY = 0;
  40726. /**
  40727. * Vignette weight or intensity of the vignette effect.
  40728. */
  40729. this.vignetteWeight = 1.5;
  40730. /**
  40731. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40732. * if vignetteEnabled is set to true.
  40733. */
  40734. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40735. /**
  40736. * Camera field of view used by the Vignette effect.
  40737. */
  40738. this.vignetteCameraFov = 0.5;
  40739. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40740. this._vignetteEnabled = false;
  40741. this._applyByPostProcess = false;
  40742. this._isEnabled = true;
  40743. /**
  40744. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40745. */
  40746. this.onUpdateParameters = new BABYLON.Observable();
  40747. }
  40748. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40749. /**
  40750. * Gets wether the color curves effect is enabled.
  40751. */
  40752. get: function () {
  40753. return this._colorCurvesEnabled;
  40754. },
  40755. /**
  40756. * Sets wether the color curves effect is enabled.
  40757. */
  40758. set: function (value) {
  40759. if (this._colorCurvesEnabled === value) {
  40760. return;
  40761. }
  40762. this._colorCurvesEnabled = value;
  40763. this._updateParameters();
  40764. },
  40765. enumerable: true,
  40766. configurable: true
  40767. });
  40768. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40769. /**
  40770. * Gets wether the color grading effect is enabled.
  40771. */
  40772. get: function () {
  40773. return this._colorGradingEnabled;
  40774. },
  40775. /**
  40776. * Sets wether the color grading effect is enabled.
  40777. */
  40778. set: function (value) {
  40779. if (this._colorGradingEnabled === value) {
  40780. return;
  40781. }
  40782. this._colorGradingEnabled = value;
  40783. this._updateParameters();
  40784. },
  40785. enumerable: true,
  40786. configurable: true
  40787. });
  40788. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40789. /**
  40790. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40791. */
  40792. get: function () {
  40793. return this._colorGradingWithGreenDepth;
  40794. },
  40795. /**
  40796. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40797. */
  40798. set: function (value) {
  40799. if (this._colorGradingWithGreenDepth === value) {
  40800. return;
  40801. }
  40802. this._colorGradingWithGreenDepth = value;
  40803. this._updateParameters();
  40804. },
  40805. enumerable: true,
  40806. configurable: true
  40807. });
  40808. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40809. /**
  40810. * Gets wether the color grading texture contains BGR values.
  40811. */
  40812. get: function () {
  40813. return this._colorGradingBGR;
  40814. },
  40815. /**
  40816. * Sets wether the color grading texture contains BGR values.
  40817. */
  40818. set: function (value) {
  40819. if (this._colorGradingBGR === value) {
  40820. return;
  40821. }
  40822. this._colorGradingBGR = value;
  40823. this._updateParameters();
  40824. },
  40825. enumerable: true,
  40826. configurable: true
  40827. });
  40828. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40829. /**
  40830. * Gets the Exposure used in the effect.
  40831. */
  40832. get: function () {
  40833. return this._exposure;
  40834. },
  40835. /**
  40836. * Sets the Exposure used in the effect.
  40837. */
  40838. set: function (value) {
  40839. if (this._exposure === value) {
  40840. return;
  40841. }
  40842. this._exposure = value;
  40843. this._updateParameters();
  40844. },
  40845. enumerable: true,
  40846. configurable: true
  40847. });
  40848. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40849. /**
  40850. * Gets wether the tone mapping effect is enabled.
  40851. */
  40852. get: function () {
  40853. return this._toneMappingEnabled;
  40854. },
  40855. /**
  40856. * Sets wether the tone mapping effect is enabled.
  40857. */
  40858. set: function (value) {
  40859. if (this._toneMappingEnabled === value) {
  40860. return;
  40861. }
  40862. this._toneMappingEnabled = value;
  40863. this._updateParameters();
  40864. },
  40865. enumerable: true,
  40866. configurable: true
  40867. });
  40868. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40869. /**
  40870. * Gets the contrast used in the effect.
  40871. */
  40872. get: function () {
  40873. return this._contrast;
  40874. },
  40875. /**
  40876. * Sets the contrast used in the effect.
  40877. */
  40878. set: function (value) {
  40879. if (this._contrast === value) {
  40880. return;
  40881. }
  40882. this._contrast = value;
  40883. this._updateParameters();
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40889. /**
  40890. * Gets the vignette blend mode allowing different kind of effect.
  40891. */
  40892. get: function () {
  40893. return this._vignetteBlendMode;
  40894. },
  40895. /**
  40896. * Sets the vignette blend mode allowing different kind of effect.
  40897. */
  40898. set: function (value) {
  40899. if (this._vignetteBlendMode === value) {
  40900. return;
  40901. }
  40902. this._vignetteBlendMode = value;
  40903. this._updateParameters();
  40904. },
  40905. enumerable: true,
  40906. configurable: true
  40907. });
  40908. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40909. /**
  40910. * Gets wether the vignette effect is enabled.
  40911. */
  40912. get: function () {
  40913. return this._vignetteEnabled;
  40914. },
  40915. /**
  40916. * Sets wether the vignette effect is enabled.
  40917. */
  40918. set: function (value) {
  40919. if (this._vignetteEnabled === value) {
  40920. return;
  40921. }
  40922. this._vignetteEnabled = value;
  40923. this._updateParameters();
  40924. },
  40925. enumerable: true,
  40926. configurable: true
  40927. });
  40928. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40929. /**
  40930. * Gets wether the image processing is applied through a post process or not.
  40931. */
  40932. get: function () {
  40933. return this._applyByPostProcess;
  40934. },
  40935. /**
  40936. * Sets wether the image processing is applied through a post process or not.
  40937. */
  40938. set: function (value) {
  40939. if (this._applyByPostProcess === value) {
  40940. return;
  40941. }
  40942. this._applyByPostProcess = value;
  40943. this._updateParameters();
  40944. },
  40945. enumerable: true,
  40946. configurable: true
  40947. });
  40948. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40949. /**
  40950. * Gets wether the image processing is enabled or not.
  40951. */
  40952. get: function () {
  40953. return this._isEnabled;
  40954. },
  40955. /**
  40956. * Sets wether the image processing is enabled or not.
  40957. */
  40958. set: function (value) {
  40959. if (this._isEnabled === value) {
  40960. return;
  40961. }
  40962. this._isEnabled = value;
  40963. this._updateParameters();
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. /**
  40969. * Method called each time the image processing information changes requires to recompile the effect.
  40970. */
  40971. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40972. this.onUpdateParameters.notifyObservers(this);
  40973. };
  40974. ImageProcessingConfiguration.prototype.getClassName = function () {
  40975. return "ImageProcessingConfiguration";
  40976. };
  40977. /**
  40978. * Prepare the list of uniforms associated with the Image Processing effects.
  40979. * @param uniformsList The list of uniforms used in the effect
  40980. * @param defines the list of defines currently in use
  40981. */
  40982. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40983. if (defines.EXPOSURE) {
  40984. uniforms.push("exposureLinear");
  40985. }
  40986. if (defines.CONTRAST) {
  40987. uniforms.push("contrast");
  40988. }
  40989. if (defines.COLORGRADING) {
  40990. uniforms.push("colorTransformSettings");
  40991. }
  40992. if (defines.VIGNETTE) {
  40993. uniforms.push("vInverseScreenSize");
  40994. uniforms.push("vignetteSettings1");
  40995. uniforms.push("vignetteSettings2");
  40996. }
  40997. if (defines.COLORCURVES) {
  40998. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40999. }
  41000. };
  41001. /**
  41002. * Prepare the list of samplers associated with the Image Processing effects.
  41003. * @param uniformsList The list of uniforms used in the effect
  41004. * @param defines the list of defines currently in use
  41005. */
  41006. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41007. if (defines.COLORGRADING) {
  41008. samplersList.push("txColorTransform");
  41009. }
  41010. };
  41011. /**
  41012. * Prepare the list of defines associated to the shader.
  41013. * @param defines the list of defines to complete
  41014. */
  41015. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41016. if (forPostProcess === void 0) { forPostProcess = false; }
  41017. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41018. defines.VIGNETTE = false;
  41019. defines.TONEMAPPING = false;
  41020. defines.CONTRAST = false;
  41021. defines.EXPOSURE = false;
  41022. defines.COLORCURVES = false;
  41023. defines.COLORGRADING = false;
  41024. defines.COLORGRADING3D = false;
  41025. defines.IMAGEPROCESSING = false;
  41026. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41027. return;
  41028. }
  41029. defines.VIGNETTE = this.vignetteEnabled;
  41030. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41031. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41032. defines.TONEMAPPING = this.toneMappingEnabled;
  41033. defines.CONTRAST = (this.contrast !== 1.0);
  41034. defines.EXPOSURE = (this.exposure !== 1.0);
  41035. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41036. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41037. if (defines.COLORGRADING) {
  41038. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41039. }
  41040. else {
  41041. defines.COLORGRADING3D = false;
  41042. }
  41043. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41044. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41045. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41046. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41047. };
  41048. /**
  41049. * Returns true if all the image processing information are ready.
  41050. */
  41051. ImageProcessingConfiguration.prototype.isReady = function () {
  41052. // Color Grading texure can not be none blocking.
  41053. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41054. };
  41055. /**
  41056. * Binds the image processing to the shader.
  41057. * @param effect The effect to bind to
  41058. */
  41059. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41060. if (aspectRatio === void 0) { aspectRatio = 1; }
  41061. // Color Curves
  41062. if (this._colorCurvesEnabled && this.colorCurves) {
  41063. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41064. }
  41065. // Vignette
  41066. if (this._vignetteEnabled) {
  41067. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41068. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41069. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41070. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41071. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41072. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41073. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41074. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41075. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41076. var vignettePower = -2.0 * this.vignetteWeight;
  41077. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41078. }
  41079. // Exposure
  41080. effect.setFloat("exposureLinear", this.exposure);
  41081. // Contrast
  41082. effect.setFloat("contrast", this.contrast);
  41083. // Color transform settings
  41084. if (this.colorGradingTexture) {
  41085. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41086. var textureSize = this.colorGradingTexture.getSize().height;
  41087. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41088. 0.5 / textureSize, // textureOffset
  41089. textureSize, // textureSize
  41090. this.colorGradingTexture.level // weight
  41091. );
  41092. }
  41093. };
  41094. /**
  41095. * Clones the current image processing instance.
  41096. * @return The cloned image processing
  41097. */
  41098. ImageProcessingConfiguration.prototype.clone = function () {
  41099. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41100. };
  41101. /**
  41102. * Serializes the current image processing instance to a json representation.
  41103. * @return a JSON representation
  41104. */
  41105. ImageProcessingConfiguration.prototype.serialize = function () {
  41106. return BABYLON.SerializationHelper.Serialize(this);
  41107. };
  41108. /**
  41109. * Parses the image processing from a json representation.
  41110. * @param source the JSON source to parse
  41111. * @return The parsed image processing
  41112. */
  41113. ImageProcessingConfiguration.Parse = function (source) {
  41114. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41115. };
  41116. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41117. /**
  41118. * Used to apply the vignette as a mix with the pixel color.
  41119. */
  41120. get: function () {
  41121. return this._VIGNETTEMODE_MULTIPLY;
  41122. },
  41123. enumerable: true,
  41124. configurable: true
  41125. });
  41126. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41127. /**
  41128. * Used to apply the vignette as a replacement of the pixel color.
  41129. */
  41130. get: function () {
  41131. return this._VIGNETTEMODE_OPAQUE;
  41132. },
  41133. enumerable: true,
  41134. configurable: true
  41135. });
  41136. // Static constants associated to the image processing.
  41137. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41138. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41139. __decorate([
  41140. BABYLON.serializeAsColorCurves()
  41141. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41142. __decorate([
  41143. BABYLON.serialize()
  41144. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41145. __decorate([
  41146. BABYLON.serializeAsTexture()
  41147. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41148. __decorate([
  41149. BABYLON.serialize()
  41150. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41151. __decorate([
  41152. BABYLON.serialize()
  41153. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41154. __decorate([
  41155. BABYLON.serialize()
  41156. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41157. __decorate([
  41158. BABYLON.serialize()
  41159. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41160. __decorate([
  41161. BABYLON.serialize()
  41162. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41163. __decorate([
  41164. BABYLON.serialize()
  41165. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41166. __decorate([
  41167. BABYLON.serialize()
  41168. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41169. __decorate([
  41170. BABYLON.serialize()
  41171. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41172. __decorate([
  41173. BABYLON.serialize()
  41174. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41175. __decorate([
  41176. BABYLON.serialize()
  41177. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41178. __decorate([
  41179. BABYLON.serializeAsColor4()
  41180. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41181. __decorate([
  41182. BABYLON.serialize()
  41183. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41184. __decorate([
  41185. BABYLON.serialize()
  41186. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41187. __decorate([
  41188. BABYLON.serialize()
  41189. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41190. __decorate([
  41191. BABYLON.serialize()
  41192. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41193. __decorate([
  41194. BABYLON.serialize()
  41195. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41196. return ImageProcessingConfiguration;
  41197. }());
  41198. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41199. })(BABYLON || (BABYLON = {}));
  41200. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41201. var BABYLON;
  41202. (function (BABYLON) {
  41203. /**
  41204. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41205. * It can help converting any input color in a desired output one. This can then be used to create effects
  41206. * from sepia, black and white to sixties or futuristic rendering...
  41207. *
  41208. * The only supported format is currently 3dl.
  41209. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41210. */
  41211. var ColorGradingTexture = /** @class */ (function (_super) {
  41212. __extends(ColorGradingTexture, _super);
  41213. /**
  41214. * Instantiates a ColorGradingTexture from the following parameters.
  41215. *
  41216. * @param url The location of the color gradind data (currently only supporting 3dl)
  41217. * @param scene The scene the texture will be used in
  41218. */
  41219. function ColorGradingTexture(url, scene) {
  41220. var _this = _super.call(this, scene) || this;
  41221. if (!url) {
  41222. return _this;
  41223. }
  41224. _this._engine = scene.getEngine();
  41225. _this._textureMatrix = BABYLON.Matrix.Identity();
  41226. _this.name = url;
  41227. _this.url = url;
  41228. _this.hasAlpha = false;
  41229. _this.isCube = false;
  41230. _this.is3D = _this._engine.webGLVersion > 1;
  41231. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41232. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41233. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41234. _this.anisotropicFilteringLevel = 1;
  41235. _this._texture = _this._getFromCache(url, true);
  41236. if (!_this._texture) {
  41237. if (!scene.useDelayedTextureLoading) {
  41238. _this.loadTexture();
  41239. }
  41240. else {
  41241. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41242. }
  41243. }
  41244. return _this;
  41245. }
  41246. /**
  41247. * Returns the texture matrix used in most of the material.
  41248. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41249. */
  41250. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41251. return this._textureMatrix;
  41252. };
  41253. /**
  41254. * Occurs when the file being loaded is a .3dl LUT file.
  41255. */
  41256. ColorGradingTexture.prototype.load3dlTexture = function () {
  41257. var engine = this._engine;
  41258. var texture;
  41259. if (engine.webGLVersion === 1) {
  41260. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41261. }
  41262. else {
  41263. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41264. }
  41265. this._texture = texture;
  41266. var callback = function (text) {
  41267. if (typeof text !== "string") {
  41268. return;
  41269. }
  41270. var data = null;
  41271. var tempData = null;
  41272. var line;
  41273. var lines = text.split('\n');
  41274. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41275. var maxColor = 0;
  41276. for (var i = 0; i < lines.length; i++) {
  41277. line = lines[i];
  41278. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41279. continue;
  41280. if (line.indexOf('#') === 0)
  41281. continue;
  41282. var words = line.split(" ");
  41283. if (size === 0) {
  41284. // Number of space + one
  41285. size = words.length;
  41286. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41287. tempData = new Float32Array(size * size * size * 4);
  41288. continue;
  41289. }
  41290. if (size != 0) {
  41291. var r = Math.max(parseInt(words[0]), 0);
  41292. var g = Math.max(parseInt(words[1]), 0);
  41293. var b = Math.max(parseInt(words[2]), 0);
  41294. maxColor = Math.max(r, maxColor);
  41295. maxColor = Math.max(g, maxColor);
  41296. maxColor = Math.max(b, maxColor);
  41297. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41298. if (tempData) {
  41299. tempData[pixelStorageIndex + 0] = r;
  41300. tempData[pixelStorageIndex + 1] = g;
  41301. tempData[pixelStorageIndex + 2] = b;
  41302. }
  41303. pixelIndexSlice++;
  41304. if (pixelIndexSlice % size == 0) {
  41305. pixelIndexH++;
  41306. pixelIndexSlice = 0;
  41307. if (pixelIndexH % size == 0) {
  41308. pixelIndexW++;
  41309. pixelIndexH = 0;
  41310. }
  41311. }
  41312. }
  41313. }
  41314. if (tempData && data) {
  41315. for (var i = 0; i < tempData.length; i++) {
  41316. if (i > 0 && (i + 1) % 4 === 0) {
  41317. data[i] = 255;
  41318. }
  41319. else {
  41320. var value = tempData[i];
  41321. data[i] = (value / maxColor * 255);
  41322. }
  41323. }
  41324. }
  41325. if (texture.is3D) {
  41326. texture.updateSize(size, size, size);
  41327. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41328. }
  41329. else {
  41330. texture.updateSize(size * size, size);
  41331. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41332. }
  41333. };
  41334. var scene = this.getScene();
  41335. if (scene) {
  41336. scene._loadFile(this.url, callback);
  41337. }
  41338. else {
  41339. this._engine._loadFile(this.url, callback);
  41340. }
  41341. return this._texture;
  41342. };
  41343. /**
  41344. * Starts the loading process of the texture.
  41345. */
  41346. ColorGradingTexture.prototype.loadTexture = function () {
  41347. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41348. this.load3dlTexture();
  41349. }
  41350. };
  41351. /**
  41352. * Clones the color gradind texture.
  41353. */
  41354. ColorGradingTexture.prototype.clone = function () {
  41355. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41356. // Base texture
  41357. newTexture.level = this.level;
  41358. return newTexture;
  41359. };
  41360. /**
  41361. * Called during delayed load for textures.
  41362. */
  41363. ColorGradingTexture.prototype.delayLoad = function () {
  41364. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41365. return;
  41366. }
  41367. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41368. this._texture = this._getFromCache(this.url, true);
  41369. if (!this._texture) {
  41370. this.loadTexture();
  41371. }
  41372. };
  41373. /**
  41374. * Parses a color grading texture serialized by Babylon.
  41375. * @param parsedTexture The texture information being parsedTexture
  41376. * @param scene The scene to load the texture in
  41377. * @param rootUrl The root url of the data assets to load
  41378. * @return A color gradind texture
  41379. */
  41380. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41381. var texture = null;
  41382. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41383. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41384. texture.name = parsedTexture.name;
  41385. texture.level = parsedTexture.level;
  41386. }
  41387. return texture;
  41388. };
  41389. /**
  41390. * Serializes the LUT texture to json format.
  41391. */
  41392. ColorGradingTexture.prototype.serialize = function () {
  41393. if (!this.name) {
  41394. return null;
  41395. }
  41396. var serializationObject = {};
  41397. serializationObject.name = this.name;
  41398. serializationObject.level = this.level;
  41399. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41400. return serializationObject;
  41401. };
  41402. /**
  41403. * Empty line regex stored for GC.
  41404. */
  41405. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41406. return ColorGradingTexture;
  41407. }(BABYLON.BaseTexture));
  41408. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41409. })(BABYLON || (BABYLON = {}));
  41410. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41411. var BABYLON;
  41412. (function (BABYLON) {
  41413. /**
  41414. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41415. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41416. * 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;
  41417. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41418. */
  41419. var ColorCurves = /** @class */ (function () {
  41420. function ColorCurves() {
  41421. this._dirty = true;
  41422. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41423. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41424. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41425. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41426. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41427. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41428. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41429. this._globalHue = 30;
  41430. this._globalDensity = 0;
  41431. this._globalSaturation = 0;
  41432. this._globalExposure = 0;
  41433. this._highlightsHue = 30;
  41434. this._highlightsDensity = 0;
  41435. this._highlightsSaturation = 0;
  41436. this._highlightsExposure = 0;
  41437. this._midtonesHue = 30;
  41438. this._midtonesDensity = 0;
  41439. this._midtonesSaturation = 0;
  41440. this._midtonesExposure = 0;
  41441. this._shadowsHue = 30;
  41442. this._shadowsDensity = 0;
  41443. this._shadowsSaturation = 0;
  41444. this._shadowsExposure = 0;
  41445. }
  41446. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41447. /**
  41448. * Gets the global Hue value.
  41449. * 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).
  41450. */
  41451. get: function () {
  41452. return this._globalHue;
  41453. },
  41454. /**
  41455. * Sets the global Hue value.
  41456. * 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).
  41457. */
  41458. set: function (value) {
  41459. this._globalHue = value;
  41460. this._dirty = true;
  41461. },
  41462. enumerable: true,
  41463. configurable: true
  41464. });
  41465. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41466. /**
  41467. * Gets the global Density value.
  41468. * 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.
  41469. * Values less than zero provide a filter of opposite hue.
  41470. */
  41471. get: function () {
  41472. return this._globalDensity;
  41473. },
  41474. /**
  41475. * Sets the global Density value.
  41476. * 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.
  41477. * Values less than zero provide a filter of opposite hue.
  41478. */
  41479. set: function (value) {
  41480. this._globalDensity = value;
  41481. this._dirty = true;
  41482. },
  41483. enumerable: true,
  41484. configurable: true
  41485. });
  41486. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41487. /**
  41488. * Gets the global Saturation value.
  41489. * 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.
  41490. */
  41491. get: function () {
  41492. return this._globalSaturation;
  41493. },
  41494. /**
  41495. * Sets the global Saturation value.
  41496. * 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.
  41497. */
  41498. set: function (value) {
  41499. this._globalSaturation = value;
  41500. this._dirty = true;
  41501. },
  41502. enumerable: true,
  41503. configurable: true
  41504. });
  41505. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41506. /**
  41507. * Gets the highlights Hue value.
  41508. * 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).
  41509. */
  41510. get: function () {
  41511. return this._highlightsHue;
  41512. },
  41513. /**
  41514. * Sets the highlights Hue value.
  41515. * 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).
  41516. */
  41517. set: function (value) {
  41518. this._highlightsHue = value;
  41519. this._dirty = true;
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41525. /**
  41526. * Gets the highlights Density value.
  41527. * 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.
  41528. * Values less than zero provide a filter of opposite hue.
  41529. */
  41530. get: function () {
  41531. return this._highlightsDensity;
  41532. },
  41533. /**
  41534. * Sets the highlights Density value.
  41535. * 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.
  41536. * Values less than zero provide a filter of opposite hue.
  41537. */
  41538. set: function (value) {
  41539. this._highlightsDensity = value;
  41540. this._dirty = true;
  41541. },
  41542. enumerable: true,
  41543. configurable: true
  41544. });
  41545. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41546. /**
  41547. * Gets the highlights Saturation value.
  41548. * 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.
  41549. */
  41550. get: function () {
  41551. return this._highlightsSaturation;
  41552. },
  41553. /**
  41554. * Sets the highlights Saturation value.
  41555. * 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.
  41556. */
  41557. set: function (value) {
  41558. this._highlightsSaturation = value;
  41559. this._dirty = true;
  41560. },
  41561. enumerable: true,
  41562. configurable: true
  41563. });
  41564. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41565. /**
  41566. * Gets the highlights Exposure value.
  41567. * 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.
  41568. */
  41569. get: function () {
  41570. return this._highlightsExposure;
  41571. },
  41572. /**
  41573. * Sets the highlights Exposure value.
  41574. * 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.
  41575. */
  41576. set: function (value) {
  41577. this._highlightsExposure = value;
  41578. this._dirty = true;
  41579. },
  41580. enumerable: true,
  41581. configurable: true
  41582. });
  41583. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41584. /**
  41585. * Gets the midtones Hue value.
  41586. * 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).
  41587. */
  41588. get: function () {
  41589. return this._midtonesHue;
  41590. },
  41591. /**
  41592. * Sets the midtones Hue value.
  41593. * 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).
  41594. */
  41595. set: function (value) {
  41596. this._midtonesHue = value;
  41597. this._dirty = true;
  41598. },
  41599. enumerable: true,
  41600. configurable: true
  41601. });
  41602. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41603. /**
  41604. * Gets the midtones Density value.
  41605. * 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.
  41606. * Values less than zero provide a filter of opposite hue.
  41607. */
  41608. get: function () {
  41609. return this._midtonesDensity;
  41610. },
  41611. /**
  41612. * Sets the midtones Density value.
  41613. * 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.
  41614. * Values less than zero provide a filter of opposite hue.
  41615. */
  41616. set: function (value) {
  41617. this._midtonesDensity = value;
  41618. this._dirty = true;
  41619. },
  41620. enumerable: true,
  41621. configurable: true
  41622. });
  41623. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41624. /**
  41625. * Gets the midtones Saturation value.
  41626. * 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.
  41627. */
  41628. get: function () {
  41629. return this._midtonesSaturation;
  41630. },
  41631. /**
  41632. * Sets the midtones Saturation value.
  41633. * 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.
  41634. */
  41635. set: function (value) {
  41636. this._midtonesSaturation = value;
  41637. this._dirty = true;
  41638. },
  41639. enumerable: true,
  41640. configurable: true
  41641. });
  41642. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41643. /**
  41644. * Gets the midtones Exposure value.
  41645. * 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.
  41646. */
  41647. get: function () {
  41648. return this._midtonesExposure;
  41649. },
  41650. /**
  41651. * Sets the midtones Exposure value.
  41652. * 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.
  41653. */
  41654. set: function (value) {
  41655. this._midtonesExposure = value;
  41656. this._dirty = true;
  41657. },
  41658. enumerable: true,
  41659. configurable: true
  41660. });
  41661. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41662. /**
  41663. * Gets the shadows Hue value.
  41664. * 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).
  41665. */
  41666. get: function () {
  41667. return this._shadowsHue;
  41668. },
  41669. /**
  41670. * Sets the shadows Hue value.
  41671. * 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).
  41672. */
  41673. set: function (value) {
  41674. this._shadowsHue = value;
  41675. this._dirty = true;
  41676. },
  41677. enumerable: true,
  41678. configurable: true
  41679. });
  41680. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41681. /**
  41682. * Gets the shadows Density value.
  41683. * 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.
  41684. * Values less than zero provide a filter of opposite hue.
  41685. */
  41686. get: function () {
  41687. return this._shadowsDensity;
  41688. },
  41689. /**
  41690. * Sets the shadows Density value.
  41691. * 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.
  41692. * Values less than zero provide a filter of opposite hue.
  41693. */
  41694. set: function (value) {
  41695. this._shadowsDensity = value;
  41696. this._dirty = true;
  41697. },
  41698. enumerable: true,
  41699. configurable: true
  41700. });
  41701. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41702. /**
  41703. * Gets the shadows Saturation value.
  41704. * 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.
  41705. */
  41706. get: function () {
  41707. return this._shadowsSaturation;
  41708. },
  41709. /**
  41710. * Sets the shadows Saturation value.
  41711. * 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.
  41712. */
  41713. set: function (value) {
  41714. this._shadowsSaturation = value;
  41715. this._dirty = true;
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41721. /**
  41722. * Gets the shadows Exposure value.
  41723. * 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.
  41724. */
  41725. get: function () {
  41726. return this._shadowsExposure;
  41727. },
  41728. /**
  41729. * Sets the shadows Exposure value.
  41730. * 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.
  41731. */
  41732. set: function (value) {
  41733. this._shadowsExposure = value;
  41734. this._dirty = true;
  41735. },
  41736. enumerable: true,
  41737. configurable: true
  41738. });
  41739. ColorCurves.prototype.getClassName = function () {
  41740. return "ColorCurves";
  41741. };
  41742. /**
  41743. * Binds the color curves to the shader.
  41744. * @param colorCurves The color curve to bind
  41745. * @param effect The effect to bind to
  41746. */
  41747. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41748. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41749. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41750. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41751. if (colorCurves._dirty) {
  41752. colorCurves._dirty = false;
  41753. // Fill in global info.
  41754. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41755. // Compute highlights info.
  41756. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41757. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41758. // Compute midtones info.
  41759. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41760. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41761. // Compute shadows info.
  41762. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41763. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41764. // Compute deltas (neutral is midtones).
  41765. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41766. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41767. }
  41768. if (effect) {
  41769. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41770. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41771. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41772. }
  41773. };
  41774. /**
  41775. * Prepare the list of uniforms associated with the ColorCurves effects.
  41776. * @param uniformsList The list of uniforms used in the effect
  41777. */
  41778. ColorCurves.PrepareUniforms = function (uniformsList) {
  41779. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41780. };
  41781. /**
  41782. * Returns color grading data based on a hue, density, saturation and exposure value.
  41783. * @param filterHue The hue of the color filter.
  41784. * @param filterDensity The density of the color filter.
  41785. * @param saturation The saturation.
  41786. * @param exposure The exposure.
  41787. * @param result The result data container.
  41788. */
  41789. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41790. if (hue == null) {
  41791. return;
  41792. }
  41793. hue = ColorCurves.clamp(hue, 0, 360);
  41794. density = ColorCurves.clamp(density, -100, 100);
  41795. saturation = ColorCurves.clamp(saturation, -100, 100);
  41796. exposure = ColorCurves.clamp(exposure, -100, 100);
  41797. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41798. // so that the maximum filter density is only 50% control. This provides fine control
  41799. // for small values and reasonable range.
  41800. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41801. density *= 0.5;
  41802. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41803. if (density < 0) {
  41804. density *= -1;
  41805. hue = (hue + 180) % 360;
  41806. }
  41807. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41808. result.scaleToRef(2, result);
  41809. result.a = 1 + 0.01 * saturation;
  41810. };
  41811. /**
  41812. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41813. * @param value The input slider value in range [-100,100].
  41814. * @returns Adjusted value.
  41815. */
  41816. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41817. value /= 100;
  41818. var x = Math.abs(value);
  41819. x = Math.pow(x, 2);
  41820. if (value < 0) {
  41821. x *= -1;
  41822. }
  41823. x *= 100;
  41824. return x;
  41825. };
  41826. /**
  41827. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41828. * @param hue The hue (H) input.
  41829. * @param saturation The saturation (S) input.
  41830. * @param brightness The brightness (B) input.
  41831. * @result An RGBA color represented as Vector4.
  41832. */
  41833. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41834. var h = ColorCurves.clamp(hue, 0, 360);
  41835. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41836. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41837. if (s === 0) {
  41838. result.r = v;
  41839. result.g = v;
  41840. result.b = v;
  41841. }
  41842. else {
  41843. // sector 0 to 5
  41844. h /= 60;
  41845. var i = Math.floor(h);
  41846. // fractional part of h
  41847. var f = h - i;
  41848. var p = v * (1 - s);
  41849. var q = v * (1 - s * f);
  41850. var t = v * (1 - s * (1 - f));
  41851. switch (i) {
  41852. case 0:
  41853. result.r = v;
  41854. result.g = t;
  41855. result.b = p;
  41856. break;
  41857. case 1:
  41858. result.r = q;
  41859. result.g = v;
  41860. result.b = p;
  41861. break;
  41862. case 2:
  41863. result.r = p;
  41864. result.g = v;
  41865. result.b = t;
  41866. break;
  41867. case 3:
  41868. result.r = p;
  41869. result.g = q;
  41870. result.b = v;
  41871. break;
  41872. case 4:
  41873. result.r = t;
  41874. result.g = p;
  41875. result.b = v;
  41876. break;
  41877. default: // case 5:
  41878. result.r = v;
  41879. result.g = p;
  41880. result.b = q;
  41881. break;
  41882. }
  41883. }
  41884. result.a = 1;
  41885. };
  41886. /**
  41887. * Returns a value clamped between min and max
  41888. * @param value The value to clamp
  41889. * @param min The minimum of value
  41890. * @param max The maximum of value
  41891. * @returns The clamped value.
  41892. */
  41893. ColorCurves.clamp = function (value, min, max) {
  41894. return Math.min(Math.max(value, min), max);
  41895. };
  41896. /**
  41897. * Clones the current color curve instance.
  41898. * @return The cloned curves
  41899. */
  41900. ColorCurves.prototype.clone = function () {
  41901. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41902. };
  41903. /**
  41904. * Serializes the current color curve instance to a json representation.
  41905. * @return a JSON representation
  41906. */
  41907. ColorCurves.prototype.serialize = function () {
  41908. return BABYLON.SerializationHelper.Serialize(this);
  41909. };
  41910. /**
  41911. * Parses the color curve from a json representation.
  41912. * @param source the JSON source to parse
  41913. * @return The parsed curves
  41914. */
  41915. ColorCurves.Parse = function (source) {
  41916. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41917. };
  41918. __decorate([
  41919. BABYLON.serialize()
  41920. ], ColorCurves.prototype, "_globalHue", void 0);
  41921. __decorate([
  41922. BABYLON.serialize()
  41923. ], ColorCurves.prototype, "_globalDensity", void 0);
  41924. __decorate([
  41925. BABYLON.serialize()
  41926. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41927. __decorate([
  41928. BABYLON.serialize()
  41929. ], ColorCurves.prototype, "_globalExposure", void 0);
  41930. __decorate([
  41931. BABYLON.serialize()
  41932. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41933. __decorate([
  41934. BABYLON.serialize()
  41935. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41936. __decorate([
  41937. BABYLON.serialize()
  41938. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41939. __decorate([
  41940. BABYLON.serialize()
  41941. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41942. __decorate([
  41943. BABYLON.serialize()
  41944. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41945. __decorate([
  41946. BABYLON.serialize()
  41947. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41948. __decorate([
  41949. BABYLON.serialize()
  41950. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41951. __decorate([
  41952. BABYLON.serialize()
  41953. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41954. return ColorCurves;
  41955. }());
  41956. BABYLON.ColorCurves = ColorCurves;
  41957. })(BABYLON || (BABYLON = {}));
  41958. //# sourceMappingURL=babylon.colorCurves.js.map
  41959. //# sourceMappingURL=babylon.behavior.js.map
  41960. var BABYLON;
  41961. (function (BABYLON) {
  41962. /**
  41963. * "Static Class" containing the most commonly used helper while dealing with material for
  41964. * rendering purpose.
  41965. *
  41966. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41967. *
  41968. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41969. */
  41970. var MaterialHelper = /** @class */ (function () {
  41971. function MaterialHelper() {
  41972. }
  41973. /**
  41974. * Bind the current view position to an effect.
  41975. * @param effect The effect to be bound
  41976. * @param scene The scene the eyes position is used from
  41977. */
  41978. MaterialHelper.BindEyePosition = function (effect, scene) {
  41979. if (scene._forcedViewPosition) {
  41980. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41981. return;
  41982. }
  41983. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41984. };
  41985. /**
  41986. * Helps preparing the defines values about the UVs in used in the effect.
  41987. * UVs are shared as much as we can accross chanels in the shaders.
  41988. * @param texture The texture we are preparing the UVs for
  41989. * @param defines The defines to update
  41990. * @param key The chanel key "diffuse", "specular"... used in the shader
  41991. */
  41992. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41993. defines._needUVs = true;
  41994. defines[key] = true;
  41995. if (texture.getTextureMatrix().isIdentity(true)) {
  41996. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41997. if (texture.coordinatesIndex === 0) {
  41998. defines["MAINUV1"] = true;
  41999. }
  42000. else {
  42001. defines["MAINUV2"] = true;
  42002. }
  42003. }
  42004. else {
  42005. defines[key + "DIRECTUV"] = 0;
  42006. }
  42007. };
  42008. /**
  42009. * Binds a texture matrix value to its corrsponding uniform
  42010. * @param texture The texture to bind the matrix for
  42011. * @param uniformBuffer The uniform buffer receivin the data
  42012. * @param key The chanel key "diffuse", "specular"... used in the shader
  42013. */
  42014. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42015. var matrix = texture.getTextureMatrix();
  42016. if (!matrix.isIdentity(true)) {
  42017. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42018. }
  42019. };
  42020. /**
  42021. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42022. * @param mesh defines the current mesh
  42023. * @param scene defines the current scene
  42024. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42025. * @param pointsCloud defines if point cloud rendering has to be turned on
  42026. * @param fogEnabled defines if fog has to be turned on
  42027. * @param alphaTest defines if alpha testing has to be turned on
  42028. * @param defines defines the current list of defines
  42029. */
  42030. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42031. if (defines._areMiscDirty) {
  42032. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42033. defines["POINTSIZE"] = pointsCloud;
  42034. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42035. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42036. defines["ALPHATEST"] = alphaTest;
  42037. }
  42038. };
  42039. /**
  42040. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42041. * @param scene defines the current scene
  42042. * @param engine defines the current engine
  42043. * @param defines specifies the list of active defines
  42044. * @param useInstances defines if instances have to be turned on
  42045. * @param useClipPlane defines if clip plane have to be turned on
  42046. */
  42047. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42048. if (useClipPlane === void 0) { useClipPlane = null; }
  42049. var changed = false;
  42050. if (useClipPlane == null) {
  42051. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42052. }
  42053. if (defines["CLIPPLANE"] !== useClipPlane) {
  42054. defines["CLIPPLANE"] = useClipPlane;
  42055. changed = true;
  42056. }
  42057. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42058. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42059. changed = true;
  42060. }
  42061. if (defines["INSTANCES"] !== useInstances) {
  42062. defines["INSTANCES"] = useInstances;
  42063. changed = true;
  42064. }
  42065. if (changed) {
  42066. defines.markAsUnprocessed();
  42067. }
  42068. };
  42069. /**
  42070. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42071. * @param mesh The mesh containing the geometry data we will draw
  42072. * @param defines The defines to update
  42073. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42074. * @param useBones Precise whether bones should be used or not (override mesh info)
  42075. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42076. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42077. * @returns false if defines are considered not dirty and have not been checked
  42078. */
  42079. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42080. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42081. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42082. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42083. return false;
  42084. }
  42085. defines._normals = defines._needNormals;
  42086. defines._uvs = defines._needUVs;
  42087. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42088. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42089. defines["TANGENT"] = true;
  42090. }
  42091. if (defines._needUVs) {
  42092. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42093. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42094. }
  42095. else {
  42096. defines["UV1"] = false;
  42097. defines["UV2"] = false;
  42098. }
  42099. if (useVertexColor) {
  42100. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42101. defines["VERTEXCOLOR"] = hasVertexColors;
  42102. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42103. }
  42104. if (useBones) {
  42105. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42106. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42107. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42108. }
  42109. else {
  42110. defines["NUM_BONE_INFLUENCERS"] = 0;
  42111. defines["BonesPerMesh"] = 0;
  42112. }
  42113. }
  42114. if (useMorphTargets) {
  42115. var manager = mesh.morphTargetManager;
  42116. if (manager) {
  42117. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42118. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42119. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42120. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42121. }
  42122. else {
  42123. defines["MORPHTARGETS_TANGENT"] = false;
  42124. defines["MORPHTARGETS_NORMAL"] = false;
  42125. defines["MORPHTARGETS"] = false;
  42126. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42127. }
  42128. }
  42129. return true;
  42130. };
  42131. /**
  42132. * Prepares the defines related to the light information passed in parameter
  42133. * @param scene The scene we are intending to draw
  42134. * @param mesh The mesh the effect is compiling for
  42135. * @param defines The defines to update
  42136. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42137. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42138. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42139. * @returns true if normals will be required for the rest of the effect
  42140. */
  42141. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42142. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42143. if (disableLighting === void 0) { disableLighting = false; }
  42144. if (!defines._areLightsDirty) {
  42145. return defines._needNormals;
  42146. }
  42147. var lightIndex = 0;
  42148. var needNormals = false;
  42149. var needRebuild = false;
  42150. var lightmapMode = false;
  42151. var shadowEnabled = false;
  42152. var specularEnabled = false;
  42153. if (scene.lightsEnabled && !disableLighting) {
  42154. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42155. var light = _a[_i];
  42156. needNormals = true;
  42157. if (defines["LIGHT" + lightIndex] === undefined) {
  42158. needRebuild = true;
  42159. }
  42160. defines["LIGHT" + lightIndex] = true;
  42161. defines["SPOTLIGHT" + lightIndex] = false;
  42162. defines["HEMILIGHT" + lightIndex] = false;
  42163. defines["POINTLIGHT" + lightIndex] = false;
  42164. defines["DIRLIGHT" + lightIndex] = false;
  42165. var type;
  42166. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42167. type = "SPOTLIGHT" + lightIndex;
  42168. var spotLight = light;
  42169. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42170. }
  42171. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42172. type = "HEMILIGHT" + lightIndex;
  42173. }
  42174. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42175. type = "POINTLIGHT" + lightIndex;
  42176. }
  42177. else {
  42178. type = "DIRLIGHT" + lightIndex;
  42179. }
  42180. defines[type] = true;
  42181. // Specular
  42182. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42183. specularEnabled = true;
  42184. }
  42185. // Shadows
  42186. defines["SHADOW" + lightIndex] = false;
  42187. defines["SHADOWPCF" + lightIndex] = false;
  42188. defines["SHADOWPCSS" + lightIndex] = false;
  42189. defines["SHADOWPOISSON" + lightIndex] = false;
  42190. defines["SHADOWESM" + lightIndex] = false;
  42191. defines["SHADOWCUBE" + lightIndex] = false;
  42192. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42193. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42194. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42195. var shadowGenerator = light.getShadowGenerator();
  42196. if (shadowGenerator) {
  42197. shadowEnabled = true;
  42198. shadowGenerator.prepareDefines(defines, lightIndex);
  42199. }
  42200. }
  42201. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42202. lightmapMode = true;
  42203. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42204. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42205. }
  42206. else {
  42207. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42208. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42209. }
  42210. lightIndex++;
  42211. if (lightIndex === maxSimultaneousLights)
  42212. break;
  42213. }
  42214. }
  42215. defines["SPECULARTERM"] = specularEnabled;
  42216. defines["SHADOWS"] = shadowEnabled;
  42217. // Resetting all other lights if any
  42218. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42219. if (defines["LIGHT" + index] !== undefined) {
  42220. defines["LIGHT" + index] = false;
  42221. defines["HEMILIGHT" + lightIndex] = false;
  42222. defines["POINTLIGHT" + lightIndex] = false;
  42223. defines["DIRLIGHT" + lightIndex] = false;
  42224. defines["SPOTLIGHT" + lightIndex] = false;
  42225. defines["SHADOW" + lightIndex] = false;
  42226. }
  42227. }
  42228. var caps = scene.getEngine().getCaps();
  42229. if (defines["SHADOWFLOAT"] === undefined) {
  42230. needRebuild = true;
  42231. }
  42232. defines["SHADOWFLOAT"] = shadowEnabled &&
  42233. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42234. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42235. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42236. if (needRebuild) {
  42237. defines.rebuild();
  42238. }
  42239. return needNormals;
  42240. };
  42241. /**
  42242. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42243. * that won t be acctive due to defines being turned off.
  42244. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42245. * @param samplersList The samplers list
  42246. * @param defines The defines helping in the list generation
  42247. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42248. */
  42249. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42250. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42251. var uniformsList;
  42252. var uniformBuffersList = null;
  42253. if (uniformsListOrOptions.uniformsNames) {
  42254. var options = uniformsListOrOptions;
  42255. uniformsList = options.uniformsNames;
  42256. uniformBuffersList = options.uniformBuffersNames;
  42257. samplersList = options.samplers;
  42258. defines = options.defines;
  42259. maxSimultaneousLights = options.maxSimultaneousLights;
  42260. }
  42261. else {
  42262. uniformsList = uniformsListOrOptions;
  42263. if (!samplersList) {
  42264. samplersList = [];
  42265. }
  42266. }
  42267. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42268. if (!defines["LIGHT" + lightIndex]) {
  42269. break;
  42270. }
  42271. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42272. if (uniformBuffersList) {
  42273. uniformBuffersList.push("Light" + lightIndex);
  42274. }
  42275. samplersList.push("shadowSampler" + lightIndex);
  42276. samplersList.push("depthSampler" + lightIndex);
  42277. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42278. samplersList.push("projectionLightSampler" + lightIndex);
  42279. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42280. }
  42281. }
  42282. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42283. uniformsList.push("morphTargetInfluences");
  42284. }
  42285. };
  42286. /**
  42287. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42288. * @param defines The defines to update while falling back
  42289. * @param fallbacks The authorized effect fallbacks
  42290. * @param maxSimultaneousLights The maximum number of lights allowed
  42291. * @param rank the current rank of the Effect
  42292. * @returns The newly affected rank
  42293. */
  42294. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42295. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42296. if (rank === void 0) { rank = 0; }
  42297. var lightFallbackRank = 0;
  42298. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42299. if (!defines["LIGHT" + lightIndex]) {
  42300. break;
  42301. }
  42302. if (lightIndex > 0) {
  42303. lightFallbackRank = rank + lightIndex;
  42304. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42305. }
  42306. if (!defines["SHADOWS"]) {
  42307. if (defines["SHADOW" + lightIndex]) {
  42308. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42309. }
  42310. if (defines["SHADOWPCF" + lightIndex]) {
  42311. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42312. }
  42313. if (defines["SHADOWPCSS" + lightIndex]) {
  42314. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42315. }
  42316. if (defines["SHADOWPOISSON" + lightIndex]) {
  42317. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42318. }
  42319. if (defines["SHADOWESM" + lightIndex]) {
  42320. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42321. }
  42322. }
  42323. }
  42324. return lightFallbackRank++;
  42325. };
  42326. /**
  42327. * Prepares the list of attributes required for morph targets according to the effect defines.
  42328. * @param attribs The current list of supported attribs
  42329. * @param mesh The mesh to prepare the morph targets attributes for
  42330. * @param defines The current Defines of the effect
  42331. */
  42332. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42333. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42334. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42335. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42336. var manager = mesh.morphTargetManager;
  42337. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42338. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42339. for (var index = 0; index < influencers; index++) {
  42340. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42341. if (normal) {
  42342. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42343. }
  42344. if (tangent) {
  42345. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42346. }
  42347. if (attribs.length > maxAttributesCount) {
  42348. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42349. }
  42350. }
  42351. }
  42352. };
  42353. /**
  42354. * Prepares the list of attributes required for bones according to the effect defines.
  42355. * @param attribs The current list of supported attribs
  42356. * @param mesh The mesh to prepare the bones attributes for
  42357. * @param defines The current Defines of the effect
  42358. * @param fallbacks The current efffect fallback strategy
  42359. */
  42360. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42361. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42362. fallbacks.addCPUSkinningFallback(0, mesh);
  42363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42365. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42368. }
  42369. }
  42370. };
  42371. /**
  42372. * Prepares the list of attributes required for instances according to the effect defines.
  42373. * @param attribs The current list of supported attribs
  42374. * @param defines The current Defines of the effect
  42375. */
  42376. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42377. if (defines["INSTANCES"]) {
  42378. attribs.push("world0");
  42379. attribs.push("world1");
  42380. attribs.push("world2");
  42381. attribs.push("world3");
  42382. }
  42383. };
  42384. /**
  42385. * Binds the light shadow information to the effect for the given mesh.
  42386. * @param light The light containing the generator
  42387. * @param scene The scene the lights belongs to
  42388. * @param mesh The mesh we are binding the information to render
  42389. * @param lightIndex The light index in the effect used to render the mesh
  42390. * @param effect The effect we are binding the data to
  42391. */
  42392. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42393. if (light.shadowEnabled && mesh.receiveShadows) {
  42394. var shadowGenerator = light.getShadowGenerator();
  42395. if (shadowGenerator) {
  42396. shadowGenerator.bindShadowLight(lightIndex, effect);
  42397. }
  42398. }
  42399. };
  42400. /**
  42401. * Binds the light information to the effect.
  42402. * @param light The light containing the generator
  42403. * @param effect The effect we are binding the data to
  42404. * @param lightIndex The light index in the effect used to render
  42405. */
  42406. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42407. light.transferToEffect(effect, lightIndex + "");
  42408. };
  42409. /**
  42410. * Binds the lights information from the scene to the effect for the given mesh.
  42411. * @param scene The scene the lights belongs to
  42412. * @param mesh The mesh we are binding the information to render
  42413. * @param effect The effect we are binding the data to
  42414. * @param defines The generated defines for the effect
  42415. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42416. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42417. */
  42418. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42419. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42420. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42421. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42422. for (var i = 0; i < len; i++) {
  42423. var light = mesh._lightSources[i];
  42424. var iAsString = i.toString();
  42425. var scaledIntensity = light.getScaledIntensity();
  42426. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42427. MaterialHelper.BindLightProperties(light, effect, i);
  42428. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42429. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42430. if (defines["SPECULARTERM"]) {
  42431. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42432. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42433. }
  42434. // Shadows
  42435. if (scene.shadowsEnabled) {
  42436. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42437. }
  42438. light._uniformBuffer.update();
  42439. }
  42440. };
  42441. /**
  42442. * Binds the fog information from the scene to the effect for the given mesh.
  42443. * @param scene The scene the lights belongs to
  42444. * @param mesh The mesh we are binding the information to render
  42445. * @param effect The effect we are binding the data to
  42446. */
  42447. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42448. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42449. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42450. effect.setColor3("vFogColor", scene.fogColor);
  42451. }
  42452. };
  42453. /**
  42454. * Binds the bones information from the mesh to the effect.
  42455. * @param mesh The mesh we are binding the information to render
  42456. * @param effect The effect we are binding the data to
  42457. */
  42458. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42459. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42460. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42461. if (matrices && effect) {
  42462. effect.setMatrices("mBones", matrices);
  42463. }
  42464. }
  42465. };
  42466. /**
  42467. * Binds the morph targets information from the mesh to the effect.
  42468. * @param abstractMesh The mesh we are binding the information to render
  42469. * @param effect The effect we are binding the data to
  42470. */
  42471. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42472. var manager = abstractMesh.morphTargetManager;
  42473. if (!abstractMesh || !manager) {
  42474. return;
  42475. }
  42476. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42477. };
  42478. /**
  42479. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42480. * @param defines The generated defines used in the effect
  42481. * @param effect The effect we are binding the data to
  42482. * @param scene The scene we are willing to render with logarithmic scale for
  42483. */
  42484. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42485. if (defines["LOGARITHMICDEPTH"]) {
  42486. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42487. }
  42488. };
  42489. /**
  42490. * Binds the clip plane information from the scene to the effect.
  42491. * @param scene The scene the clip plane information are extracted from
  42492. * @param effect The effect we are binding the data to
  42493. */
  42494. MaterialHelper.BindClipPlane = function (effect, scene) {
  42495. if (scene.clipPlane) {
  42496. var clipPlane = scene.clipPlane;
  42497. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42498. }
  42499. };
  42500. return MaterialHelper;
  42501. }());
  42502. BABYLON.MaterialHelper = MaterialHelper;
  42503. })(BABYLON || (BABYLON = {}));
  42504. //# sourceMappingURL=babylon.materialHelper.js.map
  42505. var BABYLON;
  42506. (function (BABYLON) {
  42507. var PushMaterial = /** @class */ (function (_super) {
  42508. __extends(PushMaterial, _super);
  42509. function PushMaterial(name, scene) {
  42510. var _this = _super.call(this, name, scene) || this;
  42511. _this._normalMatrix = new BABYLON.Matrix();
  42512. _this.storeEffectOnSubMeshes = true;
  42513. return _this;
  42514. }
  42515. PushMaterial.prototype.getEffect = function () {
  42516. return this._activeEffect;
  42517. };
  42518. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42519. if (!mesh) {
  42520. return false;
  42521. }
  42522. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42523. return true;
  42524. }
  42525. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42526. };
  42527. /**
  42528. * Binds the given world matrix to the active effect
  42529. *
  42530. * @param world the matrix to bind
  42531. */
  42532. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42533. this._activeEffect.setMatrix("world", world);
  42534. };
  42535. /**
  42536. * Binds the given normal matrix to the active effect
  42537. *
  42538. * @param normalMatrix the matrix to bind
  42539. */
  42540. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42541. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42542. };
  42543. PushMaterial.prototype.bind = function (world, mesh) {
  42544. if (!mesh) {
  42545. return;
  42546. }
  42547. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42548. };
  42549. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42550. if (effect === void 0) { effect = null; }
  42551. _super.prototype._afterBind.call(this, mesh);
  42552. this.getScene()._cachedEffect = effect;
  42553. };
  42554. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42555. if (visibility === void 0) { visibility = 1; }
  42556. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42557. };
  42558. return PushMaterial;
  42559. }(BABYLON.Material));
  42560. BABYLON.PushMaterial = PushMaterial;
  42561. })(BABYLON || (BABYLON = {}));
  42562. //# sourceMappingURL=babylon.pushMaterial.js.map
  42563. var BABYLON;
  42564. (function (BABYLON) {
  42565. /** @hidden */
  42566. var StandardMaterialDefines = /** @class */ (function (_super) {
  42567. __extends(StandardMaterialDefines, _super);
  42568. function StandardMaterialDefines() {
  42569. var _this = _super.call(this) || this;
  42570. _this.MAINUV1 = false;
  42571. _this.MAINUV2 = false;
  42572. _this.DIFFUSE = false;
  42573. _this.DIFFUSEDIRECTUV = 0;
  42574. _this.AMBIENT = false;
  42575. _this.AMBIENTDIRECTUV = 0;
  42576. _this.OPACITY = false;
  42577. _this.OPACITYDIRECTUV = 0;
  42578. _this.OPACITYRGB = false;
  42579. _this.REFLECTION = false;
  42580. _this.EMISSIVE = false;
  42581. _this.EMISSIVEDIRECTUV = 0;
  42582. _this.SPECULAR = false;
  42583. _this.SPECULARDIRECTUV = 0;
  42584. _this.BUMP = false;
  42585. _this.BUMPDIRECTUV = 0;
  42586. _this.PARALLAX = false;
  42587. _this.PARALLAXOCCLUSION = false;
  42588. _this.SPECULAROVERALPHA = false;
  42589. _this.CLIPPLANE = false;
  42590. _this.ALPHATEST = false;
  42591. _this.DEPTHPREPASS = false;
  42592. _this.ALPHAFROMDIFFUSE = false;
  42593. _this.POINTSIZE = false;
  42594. _this.FOG = false;
  42595. _this.SPECULARTERM = false;
  42596. _this.DIFFUSEFRESNEL = false;
  42597. _this.OPACITYFRESNEL = false;
  42598. _this.REFLECTIONFRESNEL = false;
  42599. _this.REFRACTIONFRESNEL = false;
  42600. _this.EMISSIVEFRESNEL = false;
  42601. _this.FRESNEL = false;
  42602. _this.NORMAL = false;
  42603. _this.UV1 = false;
  42604. _this.UV2 = false;
  42605. _this.VERTEXCOLOR = false;
  42606. _this.VERTEXALPHA = false;
  42607. _this.NUM_BONE_INFLUENCERS = 0;
  42608. _this.BonesPerMesh = 0;
  42609. _this.INSTANCES = false;
  42610. _this.GLOSSINESS = false;
  42611. _this.ROUGHNESS = false;
  42612. _this.EMISSIVEASILLUMINATION = false;
  42613. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42614. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42615. _this.LIGHTMAP = false;
  42616. _this.LIGHTMAPDIRECTUV = 0;
  42617. _this.OBJECTSPACE_NORMALMAP = false;
  42618. _this.USELIGHTMAPASSHADOWMAP = false;
  42619. _this.REFLECTIONMAP_3D = false;
  42620. _this.REFLECTIONMAP_SPHERICAL = false;
  42621. _this.REFLECTIONMAP_PLANAR = false;
  42622. _this.REFLECTIONMAP_CUBIC = false;
  42623. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42624. _this.REFLECTIONMAP_PROJECTION = false;
  42625. _this.REFLECTIONMAP_SKYBOX = false;
  42626. _this.REFLECTIONMAP_EXPLICIT = false;
  42627. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42628. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42629. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42630. _this.INVERTCUBICMAP = false;
  42631. _this.LOGARITHMICDEPTH = false;
  42632. _this.REFRACTION = false;
  42633. _this.REFRACTIONMAP_3D = false;
  42634. _this.REFLECTIONOVERALPHA = false;
  42635. _this.TWOSIDEDLIGHTING = false;
  42636. _this.SHADOWFLOAT = false;
  42637. _this.MORPHTARGETS = false;
  42638. _this.MORPHTARGETS_NORMAL = false;
  42639. _this.MORPHTARGETS_TANGENT = false;
  42640. _this.NUM_MORPH_INFLUENCERS = 0;
  42641. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42642. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42643. _this.IMAGEPROCESSING = false;
  42644. _this.VIGNETTE = false;
  42645. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42646. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42647. _this.TONEMAPPING = false;
  42648. _this.CONTRAST = false;
  42649. _this.COLORCURVES = false;
  42650. _this.COLORGRADING = false;
  42651. _this.COLORGRADING3D = false;
  42652. _this.SAMPLER3DGREENDEPTH = false;
  42653. _this.SAMPLER3DBGRMAP = false;
  42654. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42655. /**
  42656. * If the reflection texture on this material is in linear color space
  42657. * @hidden
  42658. */
  42659. _this.IS_REFLECTION_LINEAR = false;
  42660. /**
  42661. * If the refraction texture on this material is in linear color space
  42662. * @hidden
  42663. */
  42664. _this.IS_REFRACTION_LINEAR = false;
  42665. _this.EXPOSURE = false;
  42666. _this.rebuild();
  42667. return _this;
  42668. }
  42669. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42670. var modes = [
  42671. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42672. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42673. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42674. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42675. ];
  42676. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42677. var mode = modes_1[_i];
  42678. this[mode] = (mode === modeToEnable);
  42679. }
  42680. };
  42681. return StandardMaterialDefines;
  42682. }(BABYLON.MaterialDefines));
  42683. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42684. var StandardMaterial = /** @class */ (function (_super) {
  42685. __extends(StandardMaterial, _super);
  42686. function StandardMaterial(name, scene) {
  42687. var _this = _super.call(this, name, scene) || this;
  42688. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42689. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42690. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42691. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42692. _this.specularPower = 64;
  42693. _this._useAlphaFromDiffuseTexture = false;
  42694. _this._useEmissiveAsIllumination = false;
  42695. _this._linkEmissiveWithDiffuse = false;
  42696. _this._useSpecularOverAlpha = false;
  42697. _this._useReflectionOverAlpha = false;
  42698. _this._disableLighting = false;
  42699. _this._useObjectSpaceNormalMap = false;
  42700. _this._useParallax = false;
  42701. _this._useParallaxOcclusion = false;
  42702. _this.parallaxScaleBias = 0.05;
  42703. _this._roughness = 0;
  42704. _this.indexOfRefraction = 0.98;
  42705. _this.invertRefractionY = true;
  42706. /**
  42707. * Defines the alpha limits in alpha test mode
  42708. */
  42709. _this.alphaCutOff = 0.4;
  42710. _this._useLightmapAsShadowmap = false;
  42711. _this._useReflectionFresnelFromSpecular = false;
  42712. _this._useGlossinessFromSpecularMapAlpha = false;
  42713. _this._maxSimultaneousLights = 4;
  42714. /**
  42715. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42716. */
  42717. _this._invertNormalMapX = false;
  42718. /**
  42719. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42720. */
  42721. _this._invertNormalMapY = false;
  42722. /**
  42723. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42724. */
  42725. _this._twoSidedLighting = false;
  42726. _this._renderTargets = new BABYLON.SmartArray(16);
  42727. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42728. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42729. // Setup the default processing configuration to the scene.
  42730. _this._attachImageProcessingConfiguration(null);
  42731. _this.getRenderTargetTextures = function () {
  42732. _this._renderTargets.reset();
  42733. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42734. _this._renderTargets.push(_this._reflectionTexture);
  42735. }
  42736. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42737. _this._renderTargets.push(_this._refractionTexture);
  42738. }
  42739. return _this._renderTargets;
  42740. };
  42741. return _this;
  42742. }
  42743. ;
  42744. ;
  42745. ;
  42746. ;
  42747. ;
  42748. ;
  42749. ;
  42750. ;
  42751. ;
  42752. ;
  42753. ;
  42754. ;
  42755. ;
  42756. ;
  42757. ;
  42758. ;
  42759. ;
  42760. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42761. /**
  42762. * Gets the image processing configuration used either in this material.
  42763. */
  42764. get: function () {
  42765. return this._imageProcessingConfiguration;
  42766. },
  42767. /**
  42768. * Sets the Default image processing configuration used either in the this material.
  42769. *
  42770. * If sets to null, the scene one is in use.
  42771. */
  42772. set: function (value) {
  42773. this._attachImageProcessingConfiguration(value);
  42774. // Ensure the effect will be rebuilt.
  42775. this._markAllSubMeshesAsTexturesDirty();
  42776. },
  42777. enumerable: true,
  42778. configurable: true
  42779. });
  42780. /**
  42781. * Attaches a new image processing configuration to the Standard Material.
  42782. * @param configuration
  42783. */
  42784. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42785. var _this = this;
  42786. if (configuration === this._imageProcessingConfiguration) {
  42787. return;
  42788. }
  42789. // Detaches observer.
  42790. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42791. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42792. }
  42793. // Pick the scene configuration if needed.
  42794. if (!configuration) {
  42795. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42796. }
  42797. else {
  42798. this._imageProcessingConfiguration = configuration;
  42799. }
  42800. // Attaches observer.
  42801. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42802. _this._markAllSubMeshesAsImageProcessingDirty();
  42803. });
  42804. };
  42805. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42806. /**
  42807. * Gets wether the color curves effect is enabled.
  42808. */
  42809. get: function () {
  42810. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42811. },
  42812. /**
  42813. * Sets wether the color curves effect is enabled.
  42814. */
  42815. set: function (value) {
  42816. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42817. },
  42818. enumerable: true,
  42819. configurable: true
  42820. });
  42821. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42822. /**
  42823. * Gets wether the color grading effect is enabled.
  42824. */
  42825. get: function () {
  42826. return this.imageProcessingConfiguration.colorGradingEnabled;
  42827. },
  42828. /**
  42829. * Gets wether the color grading effect is enabled.
  42830. */
  42831. set: function (value) {
  42832. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42838. /**
  42839. * Gets wether tonemapping is enabled or not.
  42840. */
  42841. get: function () {
  42842. return this._imageProcessingConfiguration.toneMappingEnabled;
  42843. },
  42844. /**
  42845. * Sets wether tonemapping is enabled or not
  42846. */
  42847. set: function (value) {
  42848. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42849. },
  42850. enumerable: true,
  42851. configurable: true
  42852. });
  42853. ;
  42854. ;
  42855. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42856. /**
  42857. * The camera exposure used on this material.
  42858. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42859. * This corresponds to a photographic exposure.
  42860. */
  42861. get: function () {
  42862. return this._imageProcessingConfiguration.exposure;
  42863. },
  42864. /**
  42865. * The camera exposure used on this material.
  42866. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42867. * This corresponds to a photographic exposure.
  42868. */
  42869. set: function (value) {
  42870. this._imageProcessingConfiguration.exposure = value;
  42871. },
  42872. enumerable: true,
  42873. configurable: true
  42874. });
  42875. ;
  42876. ;
  42877. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42878. /**
  42879. * Gets The camera contrast used on this material.
  42880. */
  42881. get: function () {
  42882. return this._imageProcessingConfiguration.contrast;
  42883. },
  42884. /**
  42885. * Sets The camera contrast used on this material.
  42886. */
  42887. set: function (value) {
  42888. this._imageProcessingConfiguration.contrast = value;
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42894. /**
  42895. * Gets the Color Grading 2D Lookup Texture.
  42896. */
  42897. get: function () {
  42898. return this._imageProcessingConfiguration.colorGradingTexture;
  42899. },
  42900. /**
  42901. * Sets the Color Grading 2D Lookup Texture.
  42902. */
  42903. set: function (value) {
  42904. this._imageProcessingConfiguration.colorGradingTexture = value;
  42905. },
  42906. enumerable: true,
  42907. configurable: true
  42908. });
  42909. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42910. /**
  42911. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42912. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42913. * 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;
  42914. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42915. */
  42916. get: function () {
  42917. return this._imageProcessingConfiguration.colorCurves;
  42918. },
  42919. /**
  42920. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42921. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42922. * 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;
  42923. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42924. */
  42925. set: function (value) {
  42926. this._imageProcessingConfiguration.colorCurves = value;
  42927. },
  42928. enumerable: true,
  42929. configurable: true
  42930. });
  42931. StandardMaterial.prototype.getClassName = function () {
  42932. return "StandardMaterial";
  42933. };
  42934. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42935. get: function () {
  42936. return this._useLogarithmicDepth;
  42937. },
  42938. set: function (value) {
  42939. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42940. this._markAllSubMeshesAsMiscDirty();
  42941. },
  42942. enumerable: true,
  42943. configurable: true
  42944. });
  42945. StandardMaterial.prototype.needAlphaBlending = function () {
  42946. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42947. };
  42948. StandardMaterial.prototype.needAlphaTesting = function () {
  42949. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42950. };
  42951. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42952. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42953. };
  42954. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42955. return this._diffuseTexture;
  42956. };
  42957. /**
  42958. * Child classes can use it to update shaders
  42959. */
  42960. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42961. if (useInstances === void 0) { useInstances = false; }
  42962. if (subMesh.effect && this.isFrozen) {
  42963. if (this._wasPreviouslyReady && subMesh.effect) {
  42964. return true;
  42965. }
  42966. }
  42967. if (!subMesh._materialDefines) {
  42968. subMesh._materialDefines = new StandardMaterialDefines();
  42969. }
  42970. var scene = this.getScene();
  42971. var defines = subMesh._materialDefines;
  42972. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42973. if (defines._renderId === scene.getRenderId()) {
  42974. return true;
  42975. }
  42976. }
  42977. var engine = scene.getEngine();
  42978. // Lights
  42979. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42980. // Textures
  42981. if (defines._areTexturesDirty) {
  42982. defines._needUVs = false;
  42983. defines.MAINUV1 = false;
  42984. defines.MAINUV2 = false;
  42985. if (scene.texturesEnabled) {
  42986. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42987. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42988. return false;
  42989. }
  42990. else {
  42991. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42992. }
  42993. }
  42994. else {
  42995. defines.DIFFUSE = false;
  42996. }
  42997. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42998. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42999. return false;
  43000. }
  43001. else {
  43002. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43003. }
  43004. }
  43005. else {
  43006. defines.AMBIENT = false;
  43007. }
  43008. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43009. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43010. return false;
  43011. }
  43012. else {
  43013. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43014. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43015. }
  43016. }
  43017. else {
  43018. defines.OPACITY = false;
  43019. }
  43020. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43021. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43022. return false;
  43023. }
  43024. else {
  43025. defines._needNormals = true;
  43026. defines.REFLECTION = true;
  43027. defines.ROUGHNESS = (this._roughness > 0);
  43028. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43029. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43030. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43031. switch (this._reflectionTexture.coordinatesMode) {
  43032. case BABYLON.Texture.CUBIC_MODE:
  43033. case BABYLON.Texture.INVCUBIC_MODE:
  43034. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43035. break;
  43036. case BABYLON.Texture.EXPLICIT_MODE:
  43037. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43038. break;
  43039. case BABYLON.Texture.PLANAR_MODE:
  43040. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43041. break;
  43042. case BABYLON.Texture.PROJECTION_MODE:
  43043. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43044. break;
  43045. case BABYLON.Texture.SKYBOX_MODE:
  43046. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43047. break;
  43048. case BABYLON.Texture.SPHERICAL_MODE:
  43049. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43050. break;
  43051. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43052. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43053. break;
  43054. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43055. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43056. break;
  43057. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43058. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43059. break;
  43060. }
  43061. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43062. }
  43063. }
  43064. else {
  43065. defines.REFLECTION = false;
  43066. }
  43067. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43068. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43069. return false;
  43070. }
  43071. else {
  43072. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43073. }
  43074. }
  43075. else {
  43076. defines.EMISSIVE = false;
  43077. }
  43078. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43079. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43080. return false;
  43081. }
  43082. else {
  43083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43084. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43085. }
  43086. }
  43087. else {
  43088. defines.LIGHTMAP = false;
  43089. }
  43090. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43091. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43092. return false;
  43093. }
  43094. else {
  43095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43096. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43097. }
  43098. }
  43099. else {
  43100. defines.SPECULAR = false;
  43101. }
  43102. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43103. // Bump texure can not be not blocking.
  43104. if (!this._bumpTexture.isReady()) {
  43105. return false;
  43106. }
  43107. else {
  43108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43109. defines.PARALLAX = this._useParallax;
  43110. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43111. }
  43112. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43113. }
  43114. else {
  43115. defines.BUMP = false;
  43116. }
  43117. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43118. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43119. return false;
  43120. }
  43121. else {
  43122. defines._needUVs = true;
  43123. defines.REFRACTION = true;
  43124. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43125. }
  43126. }
  43127. else {
  43128. defines.REFRACTION = false;
  43129. }
  43130. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43131. }
  43132. else {
  43133. defines.DIFFUSE = false;
  43134. defines.AMBIENT = false;
  43135. defines.OPACITY = false;
  43136. defines.REFLECTION = false;
  43137. defines.EMISSIVE = false;
  43138. defines.LIGHTMAP = false;
  43139. defines.BUMP = false;
  43140. defines.REFRACTION = false;
  43141. }
  43142. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43143. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43144. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43145. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43146. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43147. }
  43148. if (defines._areImageProcessingDirty) {
  43149. if (!this._imageProcessingConfiguration.isReady()) {
  43150. return false;
  43151. }
  43152. this._imageProcessingConfiguration.prepareDefines(defines);
  43153. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43154. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43155. }
  43156. if (defines._areFresnelDirty) {
  43157. if (StandardMaterial.FresnelEnabled) {
  43158. // Fresnel
  43159. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43160. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43161. this._reflectionFresnelParameters) {
  43162. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43163. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43164. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43165. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43166. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43167. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43168. defines._needNormals = true;
  43169. defines.FRESNEL = true;
  43170. }
  43171. }
  43172. else {
  43173. defines.FRESNEL = false;
  43174. }
  43175. }
  43176. // Misc.
  43177. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43178. // Attribs
  43179. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43180. // Values that need to be evaluated on every frame
  43181. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43182. // Get correct effect
  43183. if (defines.isDirty) {
  43184. defines.markAsProcessed();
  43185. scene.resetCachedMaterial();
  43186. // Fallbacks
  43187. var fallbacks = new BABYLON.EffectFallbacks();
  43188. if (defines.REFLECTION) {
  43189. fallbacks.addFallback(0, "REFLECTION");
  43190. }
  43191. if (defines.SPECULAR) {
  43192. fallbacks.addFallback(0, "SPECULAR");
  43193. }
  43194. if (defines.BUMP) {
  43195. fallbacks.addFallback(0, "BUMP");
  43196. }
  43197. if (defines.PARALLAX) {
  43198. fallbacks.addFallback(1, "PARALLAX");
  43199. }
  43200. if (defines.PARALLAXOCCLUSION) {
  43201. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43202. }
  43203. if (defines.SPECULAROVERALPHA) {
  43204. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43205. }
  43206. if (defines.FOG) {
  43207. fallbacks.addFallback(1, "FOG");
  43208. }
  43209. if (defines.POINTSIZE) {
  43210. fallbacks.addFallback(0, "POINTSIZE");
  43211. }
  43212. if (defines.LOGARITHMICDEPTH) {
  43213. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43214. }
  43215. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43216. if (defines.SPECULARTERM) {
  43217. fallbacks.addFallback(0, "SPECULARTERM");
  43218. }
  43219. if (defines.DIFFUSEFRESNEL) {
  43220. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43221. }
  43222. if (defines.OPACITYFRESNEL) {
  43223. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43224. }
  43225. if (defines.REFLECTIONFRESNEL) {
  43226. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43227. }
  43228. if (defines.EMISSIVEFRESNEL) {
  43229. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43230. }
  43231. if (defines.FRESNEL) {
  43232. fallbacks.addFallback(4, "FRESNEL");
  43233. }
  43234. //Attributes
  43235. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43236. if (defines.NORMAL) {
  43237. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43238. }
  43239. if (defines.UV1) {
  43240. attribs.push(BABYLON.VertexBuffer.UVKind);
  43241. }
  43242. if (defines.UV2) {
  43243. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43244. }
  43245. if (defines.VERTEXCOLOR) {
  43246. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43247. }
  43248. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43249. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43250. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43251. var shaderName = "default";
  43252. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43253. "vFogInfos", "vFogColor", "pointSize",
  43254. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43255. "mBones",
  43256. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43257. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43258. "vReflectionPosition", "vReflectionSize",
  43259. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43260. ];
  43261. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43262. var uniformBuffers = ["Material", "Scene"];
  43263. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43264. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43265. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43266. uniformsNames: uniforms,
  43267. uniformBuffersNames: uniformBuffers,
  43268. samplers: samplers,
  43269. defines: defines,
  43270. maxSimultaneousLights: this._maxSimultaneousLights
  43271. });
  43272. if (this.customShaderNameResolve) {
  43273. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43274. }
  43275. var join = defines.toString();
  43276. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43277. attributes: attribs,
  43278. uniformsNames: uniforms,
  43279. uniformBuffersNames: uniformBuffers,
  43280. samplers: samplers,
  43281. defines: join,
  43282. fallbacks: fallbacks,
  43283. onCompiled: this.onCompiled,
  43284. onError: this.onError,
  43285. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43286. }, engine), defines);
  43287. this.buildUniformLayout();
  43288. }
  43289. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43290. return false;
  43291. }
  43292. defines._renderId = scene.getRenderId();
  43293. this._wasPreviouslyReady = true;
  43294. return true;
  43295. };
  43296. StandardMaterial.prototype.buildUniformLayout = function () {
  43297. // Order is important !
  43298. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43299. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43300. this._uniformBuffer.addUniform("opacityParts", 4);
  43301. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43302. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43303. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43304. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43305. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43306. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43307. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43308. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43309. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43310. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43311. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43312. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43313. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43314. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43315. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43316. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43317. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43318. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43319. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43320. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43321. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43322. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43323. this._uniformBuffer.addUniform("specularMatrix", 16);
  43324. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43325. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43326. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43327. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43328. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43329. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43330. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43331. this._uniformBuffer.addUniform("pointSize", 1);
  43332. this._uniformBuffer.create();
  43333. };
  43334. StandardMaterial.prototype.unbind = function () {
  43335. if (this._activeEffect) {
  43336. var needFlag = false;
  43337. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43338. this._activeEffect.setTexture("reflection2DSampler", null);
  43339. needFlag = true;
  43340. }
  43341. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43342. this._activeEffect.setTexture("refraction2DSampler", null);
  43343. needFlag = true;
  43344. }
  43345. if (needFlag) {
  43346. this._markAllSubMeshesAsTexturesDirty();
  43347. }
  43348. }
  43349. _super.prototype.unbind.call(this);
  43350. };
  43351. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43352. var scene = this.getScene();
  43353. var defines = subMesh._materialDefines;
  43354. if (!defines) {
  43355. return;
  43356. }
  43357. var effect = subMesh.effect;
  43358. if (!effect) {
  43359. return;
  43360. }
  43361. this._activeEffect = effect;
  43362. // Matrices
  43363. this.bindOnlyWorldMatrix(world);
  43364. // Normal Matrix
  43365. if (defines.OBJECTSPACE_NORMALMAP) {
  43366. world.toNormalMatrix(this._normalMatrix);
  43367. this.bindOnlyNormalMatrix(this._normalMatrix);
  43368. }
  43369. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43370. // Bones
  43371. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43372. if (mustRebind) {
  43373. this._uniformBuffer.bindToEffect(effect, "Material");
  43374. this.bindViewProjection(effect);
  43375. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43376. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43377. // Fresnel
  43378. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43379. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43380. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43381. }
  43382. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43383. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43384. }
  43385. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43386. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43387. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43388. }
  43389. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43390. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43391. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43392. }
  43393. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43394. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43395. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43396. }
  43397. }
  43398. // Textures
  43399. if (scene.texturesEnabled) {
  43400. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43401. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43402. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43403. if (this._diffuseTexture.hasAlpha) {
  43404. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43405. }
  43406. }
  43407. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43408. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43409. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43410. }
  43411. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43412. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43413. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43414. }
  43415. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43416. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43417. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43418. if (this._reflectionTexture.boundingBoxSize) {
  43419. var cubeTexture = this._reflectionTexture;
  43420. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43421. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43422. }
  43423. }
  43424. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43425. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43426. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43427. }
  43428. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43429. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43430. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43431. }
  43432. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43433. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43434. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43435. }
  43436. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43437. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43438. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43439. if (scene._mirroredCameraPosition) {
  43440. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43441. }
  43442. else {
  43443. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43444. }
  43445. }
  43446. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43447. var depth = 1.0;
  43448. if (!this._refractionTexture.isCube) {
  43449. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43450. if (this._refractionTexture.depth) {
  43451. depth = this._refractionTexture.depth;
  43452. }
  43453. }
  43454. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43455. }
  43456. }
  43457. // Point size
  43458. if (this.pointsCloud) {
  43459. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43460. }
  43461. if (defines.SPECULARTERM) {
  43462. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43463. }
  43464. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43465. // Diffuse
  43466. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43467. }
  43468. // Textures
  43469. if (scene.texturesEnabled) {
  43470. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43471. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43472. }
  43473. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43474. effect.setTexture("ambientSampler", this._ambientTexture);
  43475. }
  43476. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43477. effect.setTexture("opacitySampler", this._opacityTexture);
  43478. }
  43479. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43480. if (this._reflectionTexture.isCube) {
  43481. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43482. }
  43483. else {
  43484. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43485. }
  43486. }
  43487. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43488. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43489. }
  43490. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43491. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43492. }
  43493. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43494. effect.setTexture("specularSampler", this._specularTexture);
  43495. }
  43496. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43497. effect.setTexture("bumpSampler", this._bumpTexture);
  43498. }
  43499. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43500. var depth = 1.0;
  43501. if (this._refractionTexture.isCube) {
  43502. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43503. }
  43504. else {
  43505. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43506. }
  43507. }
  43508. }
  43509. // Clip plane
  43510. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43511. // Colors
  43512. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43513. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43514. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43515. }
  43516. if (mustRebind || !this.isFrozen) {
  43517. // Lights
  43518. if (scene.lightsEnabled && !this._disableLighting) {
  43519. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43520. }
  43521. // View
  43522. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43523. this.bindView(effect);
  43524. }
  43525. // Fog
  43526. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43527. // Morph targets
  43528. if (defines.NUM_MORPH_INFLUENCERS) {
  43529. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43530. }
  43531. // Log. depth
  43532. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43533. // image processing
  43534. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43535. this._imageProcessingConfiguration.bind(this._activeEffect);
  43536. }
  43537. }
  43538. this._uniformBuffer.update();
  43539. this._afterBind(mesh, this._activeEffect);
  43540. };
  43541. StandardMaterial.prototype.getAnimatables = function () {
  43542. var results = [];
  43543. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43544. results.push(this._diffuseTexture);
  43545. }
  43546. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43547. results.push(this._ambientTexture);
  43548. }
  43549. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43550. results.push(this._opacityTexture);
  43551. }
  43552. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43553. results.push(this._reflectionTexture);
  43554. }
  43555. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43556. results.push(this._emissiveTexture);
  43557. }
  43558. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43559. results.push(this._specularTexture);
  43560. }
  43561. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43562. results.push(this._bumpTexture);
  43563. }
  43564. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43565. results.push(this._lightmapTexture);
  43566. }
  43567. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43568. results.push(this._refractionTexture);
  43569. }
  43570. return results;
  43571. };
  43572. StandardMaterial.prototype.getActiveTextures = function () {
  43573. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43574. if (this._diffuseTexture) {
  43575. activeTextures.push(this._diffuseTexture);
  43576. }
  43577. if (this._ambientTexture) {
  43578. activeTextures.push(this._ambientTexture);
  43579. }
  43580. if (this._opacityTexture) {
  43581. activeTextures.push(this._opacityTexture);
  43582. }
  43583. if (this._reflectionTexture) {
  43584. activeTextures.push(this._reflectionTexture);
  43585. }
  43586. if (this._emissiveTexture) {
  43587. activeTextures.push(this._emissiveTexture);
  43588. }
  43589. if (this._specularTexture) {
  43590. activeTextures.push(this._specularTexture);
  43591. }
  43592. if (this._bumpTexture) {
  43593. activeTextures.push(this._bumpTexture);
  43594. }
  43595. if (this._lightmapTexture) {
  43596. activeTextures.push(this._lightmapTexture);
  43597. }
  43598. if (this._refractionTexture) {
  43599. activeTextures.push(this._refractionTexture);
  43600. }
  43601. return activeTextures;
  43602. };
  43603. StandardMaterial.prototype.hasTexture = function (texture) {
  43604. if (_super.prototype.hasTexture.call(this, texture)) {
  43605. return true;
  43606. }
  43607. if (this._diffuseTexture === texture) {
  43608. return true;
  43609. }
  43610. if (this._ambientTexture === texture) {
  43611. return true;
  43612. }
  43613. if (this._opacityTexture === texture) {
  43614. return true;
  43615. }
  43616. if (this._reflectionTexture === texture) {
  43617. return true;
  43618. }
  43619. if (this._emissiveTexture === texture) {
  43620. return true;
  43621. }
  43622. if (this._specularTexture === texture) {
  43623. return true;
  43624. }
  43625. if (this._bumpTexture === texture) {
  43626. return true;
  43627. }
  43628. if (this._lightmapTexture === texture) {
  43629. return true;
  43630. }
  43631. if (this._refractionTexture === texture) {
  43632. return true;
  43633. }
  43634. return false;
  43635. };
  43636. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43637. if (forceDisposeTextures) {
  43638. if (this._diffuseTexture) {
  43639. this._diffuseTexture.dispose();
  43640. }
  43641. if (this._ambientTexture) {
  43642. this._ambientTexture.dispose();
  43643. }
  43644. if (this._opacityTexture) {
  43645. this._opacityTexture.dispose();
  43646. }
  43647. if (this._reflectionTexture) {
  43648. this._reflectionTexture.dispose();
  43649. }
  43650. if (this._emissiveTexture) {
  43651. this._emissiveTexture.dispose();
  43652. }
  43653. if (this._specularTexture) {
  43654. this._specularTexture.dispose();
  43655. }
  43656. if (this._bumpTexture) {
  43657. this._bumpTexture.dispose();
  43658. }
  43659. if (this._lightmapTexture) {
  43660. this._lightmapTexture.dispose();
  43661. }
  43662. if (this._refractionTexture) {
  43663. this._refractionTexture.dispose();
  43664. }
  43665. }
  43666. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43667. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43668. }
  43669. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43670. };
  43671. StandardMaterial.prototype.clone = function (name) {
  43672. var _this = this;
  43673. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43674. result.name = name;
  43675. result.id = name;
  43676. return result;
  43677. };
  43678. StandardMaterial.prototype.serialize = function () {
  43679. return BABYLON.SerializationHelper.Serialize(this);
  43680. };
  43681. // Statics
  43682. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43683. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43684. };
  43685. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43686. get: function () {
  43687. return StandardMaterial._DiffuseTextureEnabled;
  43688. },
  43689. set: function (value) {
  43690. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43691. return;
  43692. }
  43693. StandardMaterial._DiffuseTextureEnabled = value;
  43694. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43695. },
  43696. enumerable: true,
  43697. configurable: true
  43698. });
  43699. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43700. get: function () {
  43701. return StandardMaterial._AmbientTextureEnabled;
  43702. },
  43703. set: function (value) {
  43704. if (StandardMaterial._AmbientTextureEnabled === value) {
  43705. return;
  43706. }
  43707. StandardMaterial._AmbientTextureEnabled = value;
  43708. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43709. },
  43710. enumerable: true,
  43711. configurable: true
  43712. });
  43713. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43714. get: function () {
  43715. return StandardMaterial._OpacityTextureEnabled;
  43716. },
  43717. set: function (value) {
  43718. if (StandardMaterial._OpacityTextureEnabled === value) {
  43719. return;
  43720. }
  43721. StandardMaterial._OpacityTextureEnabled = value;
  43722. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43728. get: function () {
  43729. return StandardMaterial._ReflectionTextureEnabled;
  43730. },
  43731. set: function (value) {
  43732. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43733. return;
  43734. }
  43735. StandardMaterial._ReflectionTextureEnabled = value;
  43736. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43737. },
  43738. enumerable: true,
  43739. configurable: true
  43740. });
  43741. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43742. get: function () {
  43743. return StandardMaterial._EmissiveTextureEnabled;
  43744. },
  43745. set: function (value) {
  43746. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43747. return;
  43748. }
  43749. StandardMaterial._EmissiveTextureEnabled = value;
  43750. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43751. },
  43752. enumerable: true,
  43753. configurable: true
  43754. });
  43755. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43756. get: function () {
  43757. return StandardMaterial._SpecularTextureEnabled;
  43758. },
  43759. set: function (value) {
  43760. if (StandardMaterial._SpecularTextureEnabled === value) {
  43761. return;
  43762. }
  43763. StandardMaterial._SpecularTextureEnabled = value;
  43764. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43765. },
  43766. enumerable: true,
  43767. configurable: true
  43768. });
  43769. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43770. get: function () {
  43771. return StandardMaterial._BumpTextureEnabled;
  43772. },
  43773. set: function (value) {
  43774. if (StandardMaterial._BumpTextureEnabled === value) {
  43775. return;
  43776. }
  43777. StandardMaterial._BumpTextureEnabled = value;
  43778. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43784. get: function () {
  43785. return StandardMaterial._LightmapTextureEnabled;
  43786. },
  43787. set: function (value) {
  43788. if (StandardMaterial._LightmapTextureEnabled === value) {
  43789. return;
  43790. }
  43791. StandardMaterial._LightmapTextureEnabled = value;
  43792. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43793. },
  43794. enumerable: true,
  43795. configurable: true
  43796. });
  43797. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43798. get: function () {
  43799. return StandardMaterial._RefractionTextureEnabled;
  43800. },
  43801. set: function (value) {
  43802. if (StandardMaterial._RefractionTextureEnabled === value) {
  43803. return;
  43804. }
  43805. StandardMaterial._RefractionTextureEnabled = value;
  43806. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43807. },
  43808. enumerable: true,
  43809. configurable: true
  43810. });
  43811. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43812. get: function () {
  43813. return StandardMaterial._ColorGradingTextureEnabled;
  43814. },
  43815. set: function (value) {
  43816. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43817. return;
  43818. }
  43819. StandardMaterial._ColorGradingTextureEnabled = value;
  43820. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43821. },
  43822. enumerable: true,
  43823. configurable: true
  43824. });
  43825. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43826. get: function () {
  43827. return StandardMaterial._FresnelEnabled;
  43828. },
  43829. set: function (value) {
  43830. if (StandardMaterial._FresnelEnabled === value) {
  43831. return;
  43832. }
  43833. StandardMaterial._FresnelEnabled = value;
  43834. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. // Flags used to enable or disable a type of texture for all Standard Materials
  43840. StandardMaterial._DiffuseTextureEnabled = true;
  43841. StandardMaterial._AmbientTextureEnabled = true;
  43842. StandardMaterial._OpacityTextureEnabled = true;
  43843. StandardMaterial._ReflectionTextureEnabled = true;
  43844. StandardMaterial._EmissiveTextureEnabled = true;
  43845. StandardMaterial._SpecularTextureEnabled = true;
  43846. StandardMaterial._BumpTextureEnabled = true;
  43847. StandardMaterial._LightmapTextureEnabled = true;
  43848. StandardMaterial._RefractionTextureEnabled = true;
  43849. StandardMaterial._ColorGradingTextureEnabled = true;
  43850. StandardMaterial._FresnelEnabled = true;
  43851. __decorate([
  43852. BABYLON.serializeAsTexture("diffuseTexture")
  43853. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43854. __decorate([
  43855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43856. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43857. __decorate([
  43858. BABYLON.serializeAsTexture("ambientTexture")
  43859. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43860. __decorate([
  43861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43862. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43863. __decorate([
  43864. BABYLON.serializeAsTexture("opacityTexture")
  43865. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43866. __decorate([
  43867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43868. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43869. __decorate([
  43870. BABYLON.serializeAsTexture("reflectionTexture")
  43871. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43872. __decorate([
  43873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43874. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43875. __decorate([
  43876. BABYLON.serializeAsTexture("emissiveTexture")
  43877. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43878. __decorate([
  43879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43880. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43881. __decorate([
  43882. BABYLON.serializeAsTexture("specularTexture")
  43883. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43884. __decorate([
  43885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43886. ], StandardMaterial.prototype, "specularTexture", void 0);
  43887. __decorate([
  43888. BABYLON.serializeAsTexture("bumpTexture")
  43889. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43890. __decorate([
  43891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43892. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43893. __decorate([
  43894. BABYLON.serializeAsTexture("lightmapTexture")
  43895. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43896. __decorate([
  43897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43898. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43899. __decorate([
  43900. BABYLON.serializeAsTexture("refractionTexture")
  43901. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43902. __decorate([
  43903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43904. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43905. __decorate([
  43906. BABYLON.serializeAsColor3("ambient")
  43907. ], StandardMaterial.prototype, "ambientColor", void 0);
  43908. __decorate([
  43909. BABYLON.serializeAsColor3("diffuse")
  43910. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43911. __decorate([
  43912. BABYLON.serializeAsColor3("specular")
  43913. ], StandardMaterial.prototype, "specularColor", void 0);
  43914. __decorate([
  43915. BABYLON.serializeAsColor3("emissive")
  43916. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43917. __decorate([
  43918. BABYLON.serialize()
  43919. ], StandardMaterial.prototype, "specularPower", void 0);
  43920. __decorate([
  43921. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43922. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43923. __decorate([
  43924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43925. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43926. __decorate([
  43927. BABYLON.serialize("useEmissiveAsIllumination")
  43928. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43929. __decorate([
  43930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43931. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43932. __decorate([
  43933. BABYLON.serialize("linkEmissiveWithDiffuse")
  43934. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43935. __decorate([
  43936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43937. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43938. __decorate([
  43939. BABYLON.serialize("useSpecularOverAlpha")
  43940. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43941. __decorate([
  43942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43943. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43944. __decorate([
  43945. BABYLON.serialize("useReflectionOverAlpha")
  43946. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43947. __decorate([
  43948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43949. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43950. __decorate([
  43951. BABYLON.serialize("disableLighting")
  43952. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43953. __decorate([
  43954. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43955. ], StandardMaterial.prototype, "disableLighting", void 0);
  43956. __decorate([
  43957. BABYLON.serialize("useObjectSpaceNormalMap")
  43958. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43959. __decorate([
  43960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43961. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43962. __decorate([
  43963. BABYLON.serialize("useParallax")
  43964. ], StandardMaterial.prototype, "_useParallax", void 0);
  43965. __decorate([
  43966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43967. ], StandardMaterial.prototype, "useParallax", void 0);
  43968. __decorate([
  43969. BABYLON.serialize("useParallaxOcclusion")
  43970. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43971. __decorate([
  43972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43973. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43974. __decorate([
  43975. BABYLON.serialize()
  43976. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43977. __decorate([
  43978. BABYLON.serialize("roughness")
  43979. ], StandardMaterial.prototype, "_roughness", void 0);
  43980. __decorate([
  43981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43982. ], StandardMaterial.prototype, "roughness", void 0);
  43983. __decorate([
  43984. BABYLON.serialize()
  43985. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43986. __decorate([
  43987. BABYLON.serialize()
  43988. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43989. __decorate([
  43990. BABYLON.serialize()
  43991. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43992. __decorate([
  43993. BABYLON.serialize("useLightmapAsShadowmap")
  43994. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43995. __decorate([
  43996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43997. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43998. __decorate([
  43999. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44000. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44001. __decorate([
  44002. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44003. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44004. __decorate([
  44005. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44006. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44007. __decorate([
  44008. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44009. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44010. __decorate([
  44011. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44012. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44013. __decorate([
  44014. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44015. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44016. __decorate([
  44017. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44018. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44019. __decorate([
  44020. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44021. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44022. __decorate([
  44023. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44024. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44025. __decorate([
  44026. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44027. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44028. __decorate([
  44029. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44030. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44031. __decorate([
  44032. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44033. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44034. __decorate([
  44035. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44036. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44037. __decorate([
  44038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44039. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44040. __decorate([
  44041. BABYLON.serialize("maxSimultaneousLights")
  44042. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44043. __decorate([
  44044. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44045. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44046. __decorate([
  44047. BABYLON.serialize("invertNormalMapX")
  44048. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44049. __decorate([
  44050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44051. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44052. __decorate([
  44053. BABYLON.serialize("invertNormalMapY")
  44054. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44055. __decorate([
  44056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44057. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44058. __decorate([
  44059. BABYLON.serialize("twoSidedLighting")
  44060. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44061. __decorate([
  44062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44063. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44064. __decorate([
  44065. BABYLON.serialize()
  44066. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44067. return StandardMaterial;
  44068. }(BABYLON.PushMaterial));
  44069. BABYLON.StandardMaterial = StandardMaterial;
  44070. })(BABYLON || (BABYLON = {}));
  44071. //# sourceMappingURL=babylon.standardMaterial.js.map
  44072. var BABYLON;
  44073. (function (BABYLON) {
  44074. /**
  44075. * Manages the defines for the PBR Material.
  44076. * @hiddenChildren
  44077. */
  44078. var PBRMaterialDefines = /** @class */ (function (_super) {
  44079. __extends(PBRMaterialDefines, _super);
  44080. /**
  44081. * Initializes the PBR Material defines.
  44082. */
  44083. function PBRMaterialDefines() {
  44084. var _this = _super.call(this) || this;
  44085. _this.PBR = true;
  44086. _this.MAINUV1 = false;
  44087. _this.MAINUV2 = false;
  44088. _this.UV1 = false;
  44089. _this.UV2 = false;
  44090. _this.ALBEDO = false;
  44091. _this.ALBEDODIRECTUV = 0;
  44092. _this.VERTEXCOLOR = false;
  44093. _this.AMBIENT = false;
  44094. _this.AMBIENTDIRECTUV = 0;
  44095. _this.AMBIENTINGRAYSCALE = false;
  44096. _this.OPACITY = false;
  44097. _this.VERTEXALPHA = false;
  44098. _this.OPACITYDIRECTUV = 0;
  44099. _this.OPACITYRGB = false;
  44100. _this.ALPHATEST = false;
  44101. _this.DEPTHPREPASS = false;
  44102. _this.ALPHABLEND = false;
  44103. _this.ALPHAFROMALBEDO = false;
  44104. _this.ALPHATESTVALUE = "0.5";
  44105. _this.SPECULAROVERALPHA = false;
  44106. _this.RADIANCEOVERALPHA = false;
  44107. _this.ALPHAFRESNEL = false;
  44108. _this.LINEARALPHAFRESNEL = false;
  44109. _this.PREMULTIPLYALPHA = false;
  44110. _this.EMISSIVE = false;
  44111. _this.EMISSIVEDIRECTUV = 0;
  44112. _this.REFLECTIVITY = false;
  44113. _this.REFLECTIVITYDIRECTUV = 0;
  44114. _this.SPECULARTERM = false;
  44115. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44116. _this.MICROSURFACEAUTOMATIC = false;
  44117. _this.LODBASEDMICROSFURACE = false;
  44118. _this.MICROSURFACEMAP = false;
  44119. _this.MICROSURFACEMAPDIRECTUV = 0;
  44120. _this.METALLICWORKFLOW = false;
  44121. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44122. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44123. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44124. _this.AOSTOREINMETALMAPRED = false;
  44125. _this.ENVIRONMENTBRDF = false;
  44126. _this.NORMAL = false;
  44127. _this.TANGENT = false;
  44128. _this.BUMP = false;
  44129. _this.BUMPDIRECTUV = 0;
  44130. _this.OBJECTSPACE_NORMALMAP = false;
  44131. _this.PARALLAX = false;
  44132. _this.PARALLAXOCCLUSION = false;
  44133. _this.NORMALXYSCALE = true;
  44134. _this.LIGHTMAP = false;
  44135. _this.LIGHTMAPDIRECTUV = 0;
  44136. _this.USELIGHTMAPASSHADOWMAP = false;
  44137. _this.GAMMALIGHTMAP = false;
  44138. _this.REFLECTION = false;
  44139. _this.REFLECTIONMAP_3D = false;
  44140. _this.REFLECTIONMAP_SPHERICAL = false;
  44141. _this.REFLECTIONMAP_PLANAR = false;
  44142. _this.REFLECTIONMAP_CUBIC = false;
  44143. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44144. _this.REFLECTIONMAP_PROJECTION = false;
  44145. _this.REFLECTIONMAP_SKYBOX = false;
  44146. _this.REFLECTIONMAP_EXPLICIT = false;
  44147. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44148. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44149. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44150. _this.INVERTCUBICMAP = false;
  44151. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44152. _this.USESPHERICALINVERTEX = false;
  44153. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44154. _this.LODINREFLECTIONALPHA = false;
  44155. _this.GAMMAREFLECTION = false;
  44156. _this.RADIANCEOCCLUSION = false;
  44157. _this.HORIZONOCCLUSION = false;
  44158. _this.REFRACTION = false;
  44159. _this.REFRACTIONMAP_3D = false;
  44160. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44161. _this.LODINREFRACTIONALPHA = false;
  44162. _this.GAMMAREFRACTION = false;
  44163. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44164. _this.INSTANCES = false;
  44165. _this.NUM_BONE_INFLUENCERS = 0;
  44166. _this.BonesPerMesh = 0;
  44167. _this.NONUNIFORMSCALING = false;
  44168. _this.MORPHTARGETS = false;
  44169. _this.MORPHTARGETS_NORMAL = false;
  44170. _this.MORPHTARGETS_TANGENT = false;
  44171. _this.NUM_MORPH_INFLUENCERS = 0;
  44172. _this.IMAGEPROCESSING = false;
  44173. _this.VIGNETTE = false;
  44174. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44175. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44176. _this.TONEMAPPING = false;
  44177. _this.CONTRAST = false;
  44178. _this.COLORCURVES = false;
  44179. _this.COLORGRADING = false;
  44180. _this.COLORGRADING3D = false;
  44181. _this.SAMPLER3DGREENDEPTH = false;
  44182. _this.SAMPLER3DBGRMAP = false;
  44183. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44184. _this.EXPOSURE = false;
  44185. _this.USEPHYSICALLIGHTFALLOFF = false;
  44186. _this.TWOSIDEDLIGHTING = false;
  44187. _this.SHADOWFLOAT = false;
  44188. _this.CLIPPLANE = false;
  44189. _this.POINTSIZE = false;
  44190. _this.FOG = false;
  44191. _this.LOGARITHMICDEPTH = false;
  44192. _this.FORCENORMALFORWARD = false;
  44193. _this.GEOMETRYAA = false;
  44194. _this.UNLIT = false;
  44195. _this.rebuild();
  44196. return _this;
  44197. }
  44198. /**
  44199. * Resets the PBR Material defines.
  44200. */
  44201. PBRMaterialDefines.prototype.reset = function () {
  44202. _super.prototype.reset.call(this);
  44203. this.ALPHATESTVALUE = "0.5";
  44204. this.PBR = true;
  44205. };
  44206. return PBRMaterialDefines;
  44207. }(BABYLON.MaterialDefines));
  44208. /**
  44209. * The Physically based material base class of BJS.
  44210. *
  44211. * This offers the main features of a standard PBR material.
  44212. * For more information, please refer to the documentation :
  44213. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44214. */
  44215. var PBRBaseMaterial = /** @class */ (function (_super) {
  44216. __extends(PBRBaseMaterial, _super);
  44217. /**
  44218. * Instantiates a new PBRMaterial instance.
  44219. *
  44220. * @param name The material name
  44221. * @param scene The scene the material will be use in.
  44222. */
  44223. function PBRBaseMaterial(name, scene) {
  44224. var _this = _super.call(this, name, scene) || this;
  44225. /**
  44226. * Intensity of the direct lights e.g. the four lights available in your scene.
  44227. * This impacts both the direct diffuse and specular highlights.
  44228. */
  44229. _this._directIntensity = 1.0;
  44230. /**
  44231. * Intensity of the emissive part of the material.
  44232. * This helps controlling the emissive effect without modifying the emissive color.
  44233. */
  44234. _this._emissiveIntensity = 1.0;
  44235. /**
  44236. * Intensity of the environment e.g. how much the environment will light the object
  44237. * either through harmonics for rough material or through the refelction for shiny ones.
  44238. */
  44239. _this._environmentIntensity = 1.0;
  44240. /**
  44241. * This is a special control allowing the reduction of the specular highlights coming from the
  44242. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44243. */
  44244. _this._specularIntensity = 1.0;
  44245. /**
  44246. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44247. */
  44248. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44249. /**
  44250. * Debug Control allowing disabling the bump map on this material.
  44251. */
  44252. _this._disableBumpMap = false;
  44253. /**
  44254. * AKA Occlusion Texture Intensity in other nomenclature.
  44255. */
  44256. _this._ambientTextureStrength = 1.0;
  44257. /**
  44258. * The color of a material in ambient lighting.
  44259. */
  44260. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44261. /**
  44262. * AKA Diffuse Color in other nomenclature.
  44263. */
  44264. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44265. /**
  44266. * AKA Specular Color in other nomenclature.
  44267. */
  44268. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44269. /**
  44270. * The color applied when light is reflected from a material.
  44271. */
  44272. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44273. /**
  44274. * The color applied when light is emitted from a material.
  44275. */
  44276. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44277. /**
  44278. * AKA Glossiness in other nomenclature.
  44279. */
  44280. _this._microSurface = 0.9;
  44281. /**
  44282. * source material index of refraction (IOR)' / 'destination material IOR.
  44283. */
  44284. _this._indexOfRefraction = 0.66;
  44285. /**
  44286. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44287. */
  44288. _this._invertRefractionY = false;
  44289. /**
  44290. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44291. * Materials half opaque for instance using refraction could benefit from this control.
  44292. */
  44293. _this._linkRefractionWithTransparency = false;
  44294. /**
  44295. * Specifies that the material will use the light map as a show map.
  44296. */
  44297. _this._useLightmapAsShadowmap = false;
  44298. /**
  44299. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44300. * makes the reflect vector face the model (under horizon).
  44301. */
  44302. _this._useHorizonOcclusion = true;
  44303. /**
  44304. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44305. * too much the area relying on ambient texture to define their ambient occlusion.
  44306. */
  44307. _this._useRadianceOcclusion = true;
  44308. /**
  44309. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44310. */
  44311. _this._useAlphaFromAlbedoTexture = false;
  44312. /**
  44313. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44314. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44315. */
  44316. _this._useSpecularOverAlpha = true;
  44317. /**
  44318. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44319. */
  44320. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44321. /**
  44322. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44323. */
  44324. _this._useRoughnessFromMetallicTextureAlpha = true;
  44325. /**
  44326. * Specifies if the metallic texture contains the roughness information in its green channel.
  44327. */
  44328. _this._useRoughnessFromMetallicTextureGreen = false;
  44329. /**
  44330. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44331. */
  44332. _this._useMetallnessFromMetallicTextureBlue = false;
  44333. /**
  44334. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44335. */
  44336. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44337. /**
  44338. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44339. */
  44340. _this._useAmbientInGrayScale = false;
  44341. /**
  44342. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44343. * The material will try to infer what glossiness each pixel should be.
  44344. */
  44345. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44346. /**
  44347. * BJS is using an harcoded light falloff based on a manually sets up range.
  44348. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44349. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44350. */
  44351. _this._usePhysicalLightFalloff = true;
  44352. /**
  44353. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44354. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44355. */
  44356. _this._useRadianceOverAlpha = true;
  44357. /**
  44358. * Allows using an object space normal map (instead of tangent space).
  44359. */
  44360. _this._useObjectSpaceNormalMap = false;
  44361. /**
  44362. * Allows using the bump map in parallax mode.
  44363. */
  44364. _this._useParallax = false;
  44365. /**
  44366. * Allows using the bump map in parallax occlusion mode.
  44367. */
  44368. _this._useParallaxOcclusion = false;
  44369. /**
  44370. * Controls the scale bias of the parallax mode.
  44371. */
  44372. _this._parallaxScaleBias = 0.05;
  44373. /**
  44374. * If sets to true, disables all the lights affecting the material.
  44375. */
  44376. _this._disableLighting = false;
  44377. /**
  44378. * Number of Simultaneous lights allowed on the material.
  44379. */
  44380. _this._maxSimultaneousLights = 4;
  44381. /**
  44382. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44383. */
  44384. _this._invertNormalMapX = false;
  44385. /**
  44386. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44387. */
  44388. _this._invertNormalMapY = false;
  44389. /**
  44390. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44391. */
  44392. _this._twoSidedLighting = false;
  44393. /**
  44394. * Defines the alpha limits in alpha test mode.
  44395. */
  44396. _this._alphaCutOff = 0.4;
  44397. /**
  44398. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44399. */
  44400. _this._forceAlphaTest = false;
  44401. /**
  44402. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44403. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44404. */
  44405. _this._useAlphaFresnel = false;
  44406. /**
  44407. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44408. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44409. */
  44410. _this._useLinearAlphaFresnel = false;
  44411. /**
  44412. * The transparency mode of the material.
  44413. */
  44414. _this._transparencyMode = null;
  44415. /**
  44416. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44417. * from cos thetav and roughness:
  44418. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44419. */
  44420. _this._environmentBRDFTexture = null;
  44421. /**
  44422. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44423. */
  44424. _this._forceIrradianceInFragment = false;
  44425. /**
  44426. * Force normal to face away from face.
  44427. */
  44428. _this._forceNormalForward = false;
  44429. /**
  44430. * Enables specular anti aliasing in the PBR shader.
  44431. * It will both interacts on the Geometry for analytical and IBL lighting.
  44432. * It also prefilter the roughness map based on the bump values.
  44433. */
  44434. _this._enableSpecularAntiAliasing = false;
  44435. /**
  44436. * Stores the available render targets.
  44437. */
  44438. _this._renderTargets = new BABYLON.SmartArray(16);
  44439. /**
  44440. * Sets the global ambient color for the material used in lighting calculations.
  44441. */
  44442. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44443. /**
  44444. * If set to true, no lighting calculations will be applied.
  44445. */
  44446. _this._unlit = false;
  44447. // Setup the default processing configuration to the scene.
  44448. _this._attachImageProcessingConfiguration(null);
  44449. _this.getRenderTargetTextures = function () {
  44450. _this._renderTargets.reset();
  44451. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44452. _this._renderTargets.push(_this._reflectionTexture);
  44453. }
  44454. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44455. _this._renderTargets.push(_this._refractionTexture);
  44456. }
  44457. return _this._renderTargets;
  44458. };
  44459. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44460. return _this;
  44461. }
  44462. /**
  44463. * Attaches a new image processing configuration to the PBR Material.
  44464. * @param configuration
  44465. */
  44466. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44467. var _this = this;
  44468. if (configuration === this._imageProcessingConfiguration) {
  44469. return;
  44470. }
  44471. // Detaches observer.
  44472. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44473. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44474. }
  44475. // Pick the scene configuration if needed.
  44476. if (!configuration) {
  44477. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44478. }
  44479. else {
  44480. this._imageProcessingConfiguration = configuration;
  44481. }
  44482. // Attaches observer.
  44483. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44484. _this._markAllSubMeshesAsImageProcessingDirty();
  44485. });
  44486. };
  44487. /**
  44488. * Gets the name of the material class.
  44489. */
  44490. PBRBaseMaterial.prototype.getClassName = function () {
  44491. return "PBRBaseMaterial";
  44492. };
  44493. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44494. /**
  44495. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44496. */
  44497. get: function () {
  44498. return this._useLogarithmicDepth;
  44499. },
  44500. /**
  44501. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44502. */
  44503. set: function (value) {
  44504. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44505. },
  44506. enumerable: true,
  44507. configurable: true
  44508. });
  44509. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44510. /**
  44511. * Gets the current transparency mode.
  44512. */
  44513. get: function () {
  44514. return this._transparencyMode;
  44515. },
  44516. /**
  44517. * Sets the transparency mode of the material.
  44518. */
  44519. set: function (value) {
  44520. if (this._transparencyMode === value) {
  44521. return;
  44522. }
  44523. this._transparencyMode = value;
  44524. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44525. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44526. },
  44527. enumerable: true,
  44528. configurable: true
  44529. });
  44530. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44531. /**
  44532. * Returns true if alpha blending should be disabled.
  44533. */
  44534. get: function () {
  44535. return (this._linkRefractionWithTransparency ||
  44536. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44537. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44538. },
  44539. enumerable: true,
  44540. configurable: true
  44541. });
  44542. /**
  44543. * Specifies whether or not this material should be rendered in alpha blend mode.
  44544. */
  44545. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44546. if (this._disableAlphaBlending) {
  44547. return false;
  44548. }
  44549. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44550. };
  44551. /**
  44552. * Specifies if the mesh will require alpha blending.
  44553. * @param mesh - BJS mesh.
  44554. */
  44555. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44556. if (this._disableAlphaBlending) {
  44557. return false;
  44558. }
  44559. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44560. };
  44561. /**
  44562. * Specifies whether or not this material should be rendered in alpha test mode.
  44563. */
  44564. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44565. if (this._forceAlphaTest) {
  44566. return true;
  44567. }
  44568. if (this._linkRefractionWithTransparency) {
  44569. return false;
  44570. }
  44571. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44572. };
  44573. /**
  44574. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44575. */
  44576. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44577. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44578. };
  44579. /**
  44580. * Gets the texture used for the alpha test.
  44581. */
  44582. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44583. return this._albedoTexture;
  44584. };
  44585. /**
  44586. * Specifies that the submesh is ready to be used.
  44587. * @param mesh - BJS mesh.
  44588. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44589. * @param useInstances - Specifies that instances should be used.
  44590. * @returns - boolean indicating that the submesh is ready or not.
  44591. */
  44592. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44593. if (subMesh.effect && this.isFrozen) {
  44594. if (this._wasPreviouslyReady) {
  44595. return true;
  44596. }
  44597. }
  44598. if (!subMesh._materialDefines) {
  44599. subMesh._materialDefines = new PBRMaterialDefines();
  44600. }
  44601. var defines = subMesh._materialDefines;
  44602. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44603. if (defines._renderId === this.getScene().getRenderId()) {
  44604. return true;
  44605. }
  44606. }
  44607. var scene = this.getScene();
  44608. var engine = scene.getEngine();
  44609. if (defines._areTexturesDirty) {
  44610. if (scene.texturesEnabled) {
  44611. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44612. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44613. return false;
  44614. }
  44615. }
  44616. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44617. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44618. return false;
  44619. }
  44620. }
  44621. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44622. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44623. return false;
  44624. }
  44625. }
  44626. var reflectionTexture = this._getReflectionTexture();
  44627. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44628. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44629. return false;
  44630. }
  44631. }
  44632. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44633. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44634. return false;
  44635. }
  44636. }
  44637. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44638. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44639. return false;
  44640. }
  44641. }
  44642. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44643. if (this._metallicTexture) {
  44644. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44645. return false;
  44646. }
  44647. }
  44648. else if (this._reflectivityTexture) {
  44649. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44650. return false;
  44651. }
  44652. }
  44653. if (this._microSurfaceTexture) {
  44654. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44655. return false;
  44656. }
  44657. }
  44658. }
  44659. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44660. // Bump texture cannot be not blocking.
  44661. if (!this._bumpTexture.isReady()) {
  44662. return false;
  44663. }
  44664. }
  44665. var refractionTexture = this._getRefractionTexture();
  44666. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44667. if (!refractionTexture.isReadyOrNotBlocking()) {
  44668. return false;
  44669. }
  44670. }
  44671. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44672. // This is blocking.
  44673. if (!this._environmentBRDFTexture.isReady()) {
  44674. return false;
  44675. }
  44676. }
  44677. }
  44678. }
  44679. if (defines._areImageProcessingDirty) {
  44680. if (!this._imageProcessingConfiguration.isReady()) {
  44681. return false;
  44682. }
  44683. }
  44684. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44685. mesh.createNormals(true);
  44686. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44687. }
  44688. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44689. if (effect) {
  44690. scene.resetCachedMaterial();
  44691. subMesh.setEffect(effect, defines);
  44692. this.buildUniformLayout();
  44693. }
  44694. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44695. return false;
  44696. }
  44697. defines._renderId = scene.getRenderId();
  44698. this._wasPreviouslyReady = true;
  44699. return true;
  44700. };
  44701. /**
  44702. * Specifies if the material uses metallic roughness workflow.
  44703. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44704. */
  44705. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44706. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44707. return true;
  44708. }
  44709. return false;
  44710. };
  44711. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44712. if (onCompiled === void 0) { onCompiled = null; }
  44713. if (onError === void 0) { onError = null; }
  44714. if (useInstances === void 0) { useInstances = null; }
  44715. if (useClipPlane === void 0) { useClipPlane = null; }
  44716. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44717. if (!defines.isDirty) {
  44718. return null;
  44719. }
  44720. defines.markAsProcessed();
  44721. var scene = this.getScene();
  44722. var engine = scene.getEngine();
  44723. // Fallbacks
  44724. var fallbacks = new BABYLON.EffectFallbacks();
  44725. var fallbackRank = 0;
  44726. if (defines.USESPHERICALINVERTEX) {
  44727. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44728. }
  44729. if (defines.FOG) {
  44730. fallbacks.addFallback(fallbackRank, "FOG");
  44731. }
  44732. if (defines.POINTSIZE) {
  44733. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44734. }
  44735. if (defines.LOGARITHMICDEPTH) {
  44736. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44737. }
  44738. if (defines.PARALLAX) {
  44739. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44740. }
  44741. if (defines.PARALLAXOCCLUSION) {
  44742. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44743. }
  44744. if (defines.ENVIRONMENTBRDF) {
  44745. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44746. }
  44747. if (defines.TANGENT) {
  44748. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44749. }
  44750. if (defines.BUMP) {
  44751. fallbacks.addFallback(fallbackRank++, "BUMP");
  44752. }
  44753. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44754. if (defines.SPECULARTERM) {
  44755. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44756. }
  44757. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44758. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44759. }
  44760. if (defines.LIGHTMAP) {
  44761. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44762. }
  44763. if (defines.NORMAL) {
  44764. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44765. }
  44766. if (defines.AMBIENT) {
  44767. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44768. }
  44769. if (defines.EMISSIVE) {
  44770. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44771. }
  44772. if (defines.VERTEXCOLOR) {
  44773. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44774. }
  44775. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44776. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44777. }
  44778. if (defines.MORPHTARGETS) {
  44779. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44780. }
  44781. //Attributes
  44782. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44783. if (defines.NORMAL) {
  44784. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44785. }
  44786. if (defines.TANGENT) {
  44787. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44788. }
  44789. if (defines.UV1) {
  44790. attribs.push(BABYLON.VertexBuffer.UVKind);
  44791. }
  44792. if (defines.UV2) {
  44793. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44794. }
  44795. if (defines.VERTEXCOLOR) {
  44796. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44797. }
  44798. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44799. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44800. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44801. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44802. "vFogInfos", "vFogColor", "pointSize",
  44803. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44804. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44805. "mBones",
  44806. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44807. "vLightingIntensity",
  44808. "logarithmicDepthConstant",
  44809. "vSphericalX", "vSphericalY", "vSphericalZ",
  44810. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44811. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44812. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44813. "vTangentSpaceParams"
  44814. ];
  44815. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44816. "bumpSampler", "lightmapSampler", "opacitySampler",
  44817. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44818. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44819. "microSurfaceSampler", "environmentBrdfSampler"];
  44820. var uniformBuffers = ["Material", "Scene"];
  44821. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44822. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44823. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44824. uniformsNames: uniforms,
  44825. uniformBuffersNames: uniformBuffers,
  44826. samplers: samplers,
  44827. defines: defines,
  44828. maxSimultaneousLights: this._maxSimultaneousLights
  44829. });
  44830. var join = defines.toString();
  44831. return engine.createEffect("pbr", {
  44832. attributes: attribs,
  44833. uniformsNames: uniforms,
  44834. uniformBuffersNames: uniformBuffers,
  44835. samplers: samplers,
  44836. defines: join,
  44837. fallbacks: fallbacks,
  44838. onCompiled: onCompiled,
  44839. onError: onError,
  44840. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44841. }, engine);
  44842. };
  44843. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44844. if (useInstances === void 0) { useInstances = null; }
  44845. if (useClipPlane === void 0) { useClipPlane = null; }
  44846. var scene = this.getScene();
  44847. var engine = scene.getEngine();
  44848. // Lights
  44849. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44850. defines._needNormals = true;
  44851. // Textures
  44852. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44853. if (defines._areTexturesDirty) {
  44854. defines._needUVs = false;
  44855. if (scene.texturesEnabled) {
  44856. if (scene.getEngine().getCaps().textureLOD) {
  44857. defines.LODBASEDMICROSFURACE = true;
  44858. }
  44859. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44861. }
  44862. else {
  44863. defines.ALBEDO = false;
  44864. }
  44865. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44867. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44868. }
  44869. else {
  44870. defines.AMBIENT = false;
  44871. }
  44872. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44873. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44874. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44875. }
  44876. else {
  44877. defines.OPACITY = false;
  44878. }
  44879. var reflectionTexture = this._getReflectionTexture();
  44880. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44881. defines.REFLECTION = true;
  44882. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44883. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44884. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44885. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44886. defines.INVERTCUBICMAP = true;
  44887. }
  44888. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44889. switch (reflectionTexture.coordinatesMode) {
  44890. case BABYLON.Texture.CUBIC_MODE:
  44891. case BABYLON.Texture.INVCUBIC_MODE:
  44892. defines.REFLECTIONMAP_CUBIC = true;
  44893. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44894. break;
  44895. case BABYLON.Texture.EXPLICIT_MODE:
  44896. defines.REFLECTIONMAP_EXPLICIT = true;
  44897. break;
  44898. case BABYLON.Texture.PLANAR_MODE:
  44899. defines.REFLECTIONMAP_PLANAR = true;
  44900. break;
  44901. case BABYLON.Texture.PROJECTION_MODE:
  44902. defines.REFLECTIONMAP_PROJECTION = true;
  44903. break;
  44904. case BABYLON.Texture.SKYBOX_MODE:
  44905. defines.REFLECTIONMAP_SKYBOX = true;
  44906. break;
  44907. case BABYLON.Texture.SPHERICAL_MODE:
  44908. defines.REFLECTIONMAP_SPHERICAL = true;
  44909. break;
  44910. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44911. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44912. break;
  44913. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44914. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44915. break;
  44916. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44917. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44918. break;
  44919. }
  44920. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44921. if (reflectionTexture.sphericalPolynomial) {
  44922. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44923. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44924. defines.USESPHERICALINVERTEX = false;
  44925. }
  44926. else {
  44927. defines.USESPHERICALINVERTEX = true;
  44928. }
  44929. }
  44930. }
  44931. }
  44932. else {
  44933. defines.REFLECTION = false;
  44934. defines.REFLECTIONMAP_3D = false;
  44935. defines.REFLECTIONMAP_SPHERICAL = false;
  44936. defines.REFLECTIONMAP_PLANAR = false;
  44937. defines.REFLECTIONMAP_CUBIC = false;
  44938. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44939. defines.REFLECTIONMAP_PROJECTION = false;
  44940. defines.REFLECTIONMAP_SKYBOX = false;
  44941. defines.REFLECTIONMAP_EXPLICIT = false;
  44942. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44943. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44944. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44945. defines.INVERTCUBICMAP = false;
  44946. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44947. defines.USESPHERICALINVERTEX = false;
  44948. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44949. defines.LODINREFLECTIONALPHA = false;
  44950. defines.GAMMAREFLECTION = false;
  44951. }
  44952. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44953. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44954. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44955. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44956. }
  44957. else {
  44958. defines.LIGHTMAP = false;
  44959. }
  44960. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44961. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44962. }
  44963. else {
  44964. defines.EMISSIVE = false;
  44965. }
  44966. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44967. if (this._metallicTexture) {
  44968. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44969. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44970. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44971. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44972. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44973. }
  44974. else if (this._reflectivityTexture) {
  44975. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44976. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44977. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44978. }
  44979. else {
  44980. defines.REFLECTIVITY = false;
  44981. }
  44982. if (this._microSurfaceTexture) {
  44983. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44984. }
  44985. else {
  44986. defines.MICROSURFACEMAP = false;
  44987. }
  44988. }
  44989. else {
  44990. defines.REFLECTIVITY = false;
  44991. defines.MICROSURFACEMAP = false;
  44992. }
  44993. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44995. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44996. defines.PARALLAX = true;
  44997. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44998. }
  44999. else {
  45000. defines.PARALLAX = false;
  45001. }
  45002. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45003. }
  45004. else {
  45005. defines.BUMP = false;
  45006. }
  45007. var refractionTexture = this._getRefractionTexture();
  45008. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45009. defines.REFRACTION = true;
  45010. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45011. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45012. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45013. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45014. if (this._linkRefractionWithTransparency) {
  45015. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45016. }
  45017. }
  45018. else {
  45019. defines.REFRACTION = false;
  45020. }
  45021. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45022. defines.ENVIRONMENTBRDF = true;
  45023. }
  45024. else {
  45025. defines.ENVIRONMENTBRDF = false;
  45026. }
  45027. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45028. defines.ALPHAFROMALBEDO = true;
  45029. }
  45030. else {
  45031. defines.ALPHAFROMALBEDO = false;
  45032. }
  45033. }
  45034. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45035. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45036. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45037. if (!this.backFaceCulling && this._twoSidedLighting) {
  45038. defines.TWOSIDEDLIGHTING = true;
  45039. }
  45040. else {
  45041. defines.TWOSIDEDLIGHTING = false;
  45042. }
  45043. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45044. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45045. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45046. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45047. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45048. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45049. }
  45050. if (defines._areImageProcessingDirty) {
  45051. this._imageProcessingConfiguration.prepareDefines(defines);
  45052. }
  45053. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45054. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45055. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45056. // Misc.
  45057. if (defines._areMiscDirty) {
  45058. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45059. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45060. }
  45061. // Values that need to be evaluated on every frame
  45062. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45063. // Attribs
  45064. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45065. };
  45066. /**
  45067. * Force shader compilation
  45068. */
  45069. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45070. var _this = this;
  45071. var localOptions = __assign({ clipPlane: false }, options);
  45072. var defines = new PBRMaterialDefines();
  45073. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45074. if (effect.isReady()) {
  45075. if (onCompiled) {
  45076. onCompiled(this);
  45077. }
  45078. }
  45079. else {
  45080. effect.onCompileObservable.add(function () {
  45081. if (onCompiled) {
  45082. onCompiled(_this);
  45083. }
  45084. });
  45085. }
  45086. };
  45087. /**
  45088. * Initializes the uniform buffer layout for the shader.
  45089. */
  45090. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45091. // Order is important !
  45092. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45093. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45094. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45095. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45096. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45097. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45098. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45099. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45100. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45101. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45102. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45103. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45104. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45105. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45106. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45107. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45108. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45109. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45110. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45111. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45112. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45113. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45114. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45115. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45116. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45117. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45118. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45119. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45120. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45121. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45122. this._uniformBuffer.addUniform("pointSize", 1);
  45123. this._uniformBuffer.create();
  45124. };
  45125. /**
  45126. * Unbinds the textures.
  45127. */
  45128. PBRBaseMaterial.prototype.unbind = function () {
  45129. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45130. this._uniformBuffer.setTexture("reflectionSampler", null);
  45131. }
  45132. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45133. this._uniformBuffer.setTexture("refractionSampler", null);
  45134. }
  45135. _super.prototype.unbind.call(this);
  45136. };
  45137. /**
  45138. * Binds the submesh data.
  45139. * @param world - The world matrix.
  45140. * @param mesh - The BJS mesh.
  45141. * @param subMesh - A submesh of the BJS mesh.
  45142. */
  45143. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45144. var scene = this.getScene();
  45145. var defines = subMesh._materialDefines;
  45146. if (!defines) {
  45147. return;
  45148. }
  45149. var effect = subMesh.effect;
  45150. if (!effect) {
  45151. return;
  45152. }
  45153. this._activeEffect = effect;
  45154. // Matrices
  45155. this.bindOnlyWorldMatrix(world);
  45156. // Normal Matrix
  45157. if (defines.OBJECTSPACE_NORMALMAP) {
  45158. world.toNormalMatrix(this._normalMatrix);
  45159. this.bindOnlyNormalMatrix(this._normalMatrix);
  45160. }
  45161. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45162. // Bones
  45163. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45164. var reflectionTexture = null;
  45165. if (mustRebind) {
  45166. this._uniformBuffer.bindToEffect(effect, "Material");
  45167. this.bindViewProjection(effect);
  45168. reflectionTexture = this._getReflectionTexture();
  45169. var refractionTexture = this._getRefractionTexture();
  45170. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45171. // Texture uniforms
  45172. if (scene.texturesEnabled) {
  45173. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45174. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45175. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45176. }
  45177. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45178. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45179. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45180. }
  45181. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45182. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45183. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45184. }
  45185. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45186. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45187. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45188. if (reflectionTexture.boundingBoxSize) {
  45189. var cubeTexture = reflectionTexture;
  45190. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45191. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45192. }
  45193. var polynomials = reflectionTexture.sphericalPolynomial;
  45194. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45195. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45196. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45197. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45198. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45199. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45200. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45201. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45202. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45203. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45204. }
  45205. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45206. }
  45207. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45208. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45209. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45210. }
  45211. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45212. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45213. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45214. }
  45215. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45216. if (this._metallicTexture) {
  45217. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45218. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45219. }
  45220. else if (this._reflectivityTexture) {
  45221. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45222. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45223. }
  45224. if (this._microSurfaceTexture) {
  45225. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45226. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45227. }
  45228. }
  45229. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45230. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45231. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45232. if (scene._mirroredCameraPosition) {
  45233. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45234. }
  45235. else {
  45236. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45237. }
  45238. }
  45239. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45240. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45241. var depth = 1.0;
  45242. if (!refractionTexture.isCube) {
  45243. if (refractionTexture.depth) {
  45244. depth = refractionTexture.depth;
  45245. }
  45246. }
  45247. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45248. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45249. }
  45250. }
  45251. // Point size
  45252. if (this.pointsCloud) {
  45253. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45254. }
  45255. // Colors
  45256. if (defines.METALLICWORKFLOW) {
  45257. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45258. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45259. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45260. }
  45261. else {
  45262. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45263. }
  45264. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45265. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45266. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45267. // Misc
  45268. this._lightingInfos.x = this._directIntensity;
  45269. this._lightingInfos.y = this._emissiveIntensity;
  45270. this._lightingInfos.z = this._environmentIntensity;
  45271. this._lightingInfos.w = this._specularIntensity;
  45272. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45273. }
  45274. // Textures
  45275. if (scene.texturesEnabled) {
  45276. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45277. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45278. }
  45279. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45280. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45281. }
  45282. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45283. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45284. }
  45285. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45286. if (defines.LODBASEDMICROSFURACE) {
  45287. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45288. }
  45289. else {
  45290. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45291. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45292. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45293. }
  45294. }
  45295. if (defines.ENVIRONMENTBRDF) {
  45296. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45297. }
  45298. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45299. if (defines.LODBASEDMICROSFURACE) {
  45300. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45301. }
  45302. else {
  45303. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45304. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45305. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45306. }
  45307. }
  45308. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45309. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45310. }
  45311. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45312. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45313. }
  45314. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45315. if (this._metallicTexture) {
  45316. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45317. }
  45318. else if (this._reflectivityTexture) {
  45319. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45320. }
  45321. if (this._microSurfaceTexture) {
  45322. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45323. }
  45324. }
  45325. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45326. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45327. }
  45328. }
  45329. // Clip plane
  45330. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45331. // Colors
  45332. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45333. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45334. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45335. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45336. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45337. }
  45338. if (mustRebind || !this.isFrozen) {
  45339. // Lights
  45340. if (scene.lightsEnabled && !this._disableLighting) {
  45341. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45342. }
  45343. // View
  45344. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45345. this.bindView(effect);
  45346. }
  45347. // Fog
  45348. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45349. // Morph targets
  45350. if (defines.NUM_MORPH_INFLUENCERS) {
  45351. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45352. }
  45353. // image processing
  45354. this._imageProcessingConfiguration.bind(this._activeEffect);
  45355. // Log. depth
  45356. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45357. }
  45358. this._uniformBuffer.update();
  45359. this._afterBind(mesh);
  45360. };
  45361. /**
  45362. * Returns the animatable textures.
  45363. * @returns - Array of animatable textures.
  45364. */
  45365. PBRBaseMaterial.prototype.getAnimatables = function () {
  45366. var results = [];
  45367. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45368. results.push(this._albedoTexture);
  45369. }
  45370. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45371. results.push(this._ambientTexture);
  45372. }
  45373. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45374. results.push(this._opacityTexture);
  45375. }
  45376. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45377. results.push(this._reflectionTexture);
  45378. }
  45379. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45380. results.push(this._emissiveTexture);
  45381. }
  45382. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45383. results.push(this._metallicTexture);
  45384. }
  45385. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45386. results.push(this._reflectivityTexture);
  45387. }
  45388. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45389. results.push(this._bumpTexture);
  45390. }
  45391. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45392. results.push(this._lightmapTexture);
  45393. }
  45394. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45395. results.push(this._refractionTexture);
  45396. }
  45397. return results;
  45398. };
  45399. /**
  45400. * Returns the texture used for reflections.
  45401. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45402. */
  45403. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45404. if (this._reflectionTexture) {
  45405. return this._reflectionTexture;
  45406. }
  45407. return this.getScene().environmentTexture;
  45408. };
  45409. /**
  45410. * Returns the texture used for refraction or null if none is used.
  45411. * @returns - Refection texture if present. If no refraction texture and refraction
  45412. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45413. */
  45414. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45415. if (this._refractionTexture) {
  45416. return this._refractionTexture;
  45417. }
  45418. if (this._linkRefractionWithTransparency) {
  45419. return this.getScene().environmentTexture;
  45420. }
  45421. return null;
  45422. };
  45423. /**
  45424. * Disposes the resources of the material.
  45425. * @param forceDisposeEffect - Forces the disposal of effects.
  45426. * @param forceDisposeTextures - Forces the disposal of all textures.
  45427. */
  45428. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45429. if (forceDisposeTextures) {
  45430. if (this._albedoTexture) {
  45431. this._albedoTexture.dispose();
  45432. }
  45433. if (this._ambientTexture) {
  45434. this._ambientTexture.dispose();
  45435. }
  45436. if (this._opacityTexture) {
  45437. this._opacityTexture.dispose();
  45438. }
  45439. if (this._reflectionTexture) {
  45440. this._reflectionTexture.dispose();
  45441. }
  45442. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45443. this._environmentBRDFTexture.dispose();
  45444. }
  45445. if (this._emissiveTexture) {
  45446. this._emissiveTexture.dispose();
  45447. }
  45448. if (this._metallicTexture) {
  45449. this._metallicTexture.dispose();
  45450. }
  45451. if (this._reflectivityTexture) {
  45452. this._reflectivityTexture.dispose();
  45453. }
  45454. if (this._bumpTexture) {
  45455. this._bumpTexture.dispose();
  45456. }
  45457. if (this._lightmapTexture) {
  45458. this._lightmapTexture.dispose();
  45459. }
  45460. if (this._refractionTexture) {
  45461. this._refractionTexture.dispose();
  45462. }
  45463. }
  45464. this._renderTargets.dispose();
  45465. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45466. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45467. }
  45468. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45469. };
  45470. /**
  45471. * Stores the reflectivity values based on metallic roughness workflow.
  45472. */
  45473. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45474. __decorate([
  45475. BABYLON.serializeAsImageProcessingConfiguration()
  45476. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45477. __decorate([
  45478. BABYLON.serialize()
  45479. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45480. __decorate([
  45481. BABYLON.serialize()
  45482. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45483. return PBRBaseMaterial;
  45484. }(BABYLON.PushMaterial));
  45485. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45486. })(BABYLON || (BABYLON = {}));
  45487. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45488. var BABYLON;
  45489. (function (BABYLON) {
  45490. /**
  45491. * The Physically based simple base material of BJS.
  45492. *
  45493. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45494. * It is used as the base class for both the specGloss and metalRough conventions.
  45495. */
  45496. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45497. __extends(PBRBaseSimpleMaterial, _super);
  45498. /**
  45499. * Instantiates a new PBRMaterial instance.
  45500. *
  45501. * @param name The material name
  45502. * @param scene The scene the material will be use in.
  45503. */
  45504. function PBRBaseSimpleMaterial(name, scene) {
  45505. var _this = _super.call(this, name, scene) || this;
  45506. /**
  45507. * Number of Simultaneous lights allowed on the material.
  45508. */
  45509. _this.maxSimultaneousLights = 4;
  45510. /**
  45511. * If sets to true, disables all the lights affecting the material.
  45512. */
  45513. _this.disableLighting = false;
  45514. /**
  45515. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45516. */
  45517. _this.invertNormalMapX = false;
  45518. /**
  45519. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45520. */
  45521. _this.invertNormalMapY = false;
  45522. /**
  45523. * Emissivie color used to self-illuminate the model.
  45524. */
  45525. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45526. /**
  45527. * Occlusion Channel Strenght.
  45528. */
  45529. _this.occlusionStrength = 1.0;
  45530. _this.useLightmapAsShadowmap = false;
  45531. _this._useAlphaFromAlbedoTexture = true;
  45532. _this._useAmbientInGrayScale = true;
  45533. return _this;
  45534. }
  45535. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45536. /**
  45537. * Gets the current double sided mode.
  45538. */
  45539. get: function () {
  45540. return this._twoSidedLighting;
  45541. },
  45542. /**
  45543. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45544. */
  45545. set: function (value) {
  45546. if (this._twoSidedLighting === value) {
  45547. return;
  45548. }
  45549. this._twoSidedLighting = value;
  45550. this.backFaceCulling = !value;
  45551. this._markAllSubMeshesAsTexturesDirty();
  45552. },
  45553. enumerable: true,
  45554. configurable: true
  45555. });
  45556. /**
  45557. * Return the active textures of the material.
  45558. */
  45559. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45560. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45561. if (this.environmentTexture) {
  45562. activeTextures.push(this.environmentTexture);
  45563. }
  45564. if (this.normalTexture) {
  45565. activeTextures.push(this.normalTexture);
  45566. }
  45567. if (this.emissiveTexture) {
  45568. activeTextures.push(this.emissiveTexture);
  45569. }
  45570. if (this.occlusionTexture) {
  45571. activeTextures.push(this.occlusionTexture);
  45572. }
  45573. if (this.lightmapTexture) {
  45574. activeTextures.push(this.lightmapTexture);
  45575. }
  45576. return activeTextures;
  45577. };
  45578. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45579. if (_super.prototype.hasTexture.call(this, texture)) {
  45580. return true;
  45581. }
  45582. if (this.lightmapTexture === texture) {
  45583. return true;
  45584. }
  45585. return false;
  45586. };
  45587. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45588. return "PBRBaseSimpleMaterial";
  45589. };
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45593. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45597. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45598. __decorate([
  45599. BABYLON.serializeAsTexture(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45601. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45610. __decorate([
  45611. BABYLON.serializeAsTexture(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45613. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45614. __decorate([
  45615. BABYLON.serializeAsColor3("emissive"),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45618. __decorate([
  45619. BABYLON.serializeAsTexture(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45625. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45626. __decorate([
  45627. BABYLON.serializeAsTexture(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45629. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45633. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45634. __decorate([
  45635. BABYLON.serialize()
  45636. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45637. __decorate([
  45638. BABYLON.serializeAsTexture(),
  45639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45640. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45641. __decorate([
  45642. BABYLON.serialize(),
  45643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45644. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45645. return PBRBaseSimpleMaterial;
  45646. }(BABYLON.PBRBaseMaterial));
  45647. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45648. })(BABYLON || (BABYLON = {}));
  45649. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45650. var BABYLON;
  45651. (function (BABYLON) {
  45652. /**
  45653. * The Physically based material of BJS.
  45654. *
  45655. * This offers the main features of a standard PBR material.
  45656. * For more information, please refer to the documentation :
  45657. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45658. */
  45659. var PBRMaterial = /** @class */ (function (_super) {
  45660. __extends(PBRMaterial, _super);
  45661. /**
  45662. * Instantiates a new PBRMaterial instance.
  45663. *
  45664. * @param name The material name
  45665. * @param scene The scene the material will be use in.
  45666. */
  45667. function PBRMaterial(name, scene) {
  45668. var _this = _super.call(this, name, scene) || this;
  45669. /**
  45670. * Intensity of the direct lights e.g. the four lights available in your scene.
  45671. * This impacts both the direct diffuse and specular highlights.
  45672. */
  45673. _this.directIntensity = 1.0;
  45674. /**
  45675. * Intensity of the emissive part of the material.
  45676. * This helps controlling the emissive effect without modifying the emissive color.
  45677. */
  45678. _this.emissiveIntensity = 1.0;
  45679. /**
  45680. * Intensity of the environment e.g. how much the environment will light the object
  45681. * either through harmonics for rough material or through the refelction for shiny ones.
  45682. */
  45683. _this.environmentIntensity = 1.0;
  45684. /**
  45685. * This is a special control allowing the reduction of the specular highlights coming from the
  45686. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45687. */
  45688. _this.specularIntensity = 1.0;
  45689. /**
  45690. * Debug Control allowing disabling the bump map on this material.
  45691. */
  45692. _this.disableBumpMap = false;
  45693. /**
  45694. * AKA Occlusion Texture Intensity in other nomenclature.
  45695. */
  45696. _this.ambientTextureStrength = 1.0;
  45697. /**
  45698. * The color of a material in ambient lighting.
  45699. */
  45700. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45701. /**
  45702. * AKA Diffuse Color in other nomenclature.
  45703. */
  45704. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45705. /**
  45706. * AKA Specular Color in other nomenclature.
  45707. */
  45708. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45709. /**
  45710. * The color reflected from the material.
  45711. */
  45712. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45713. /**
  45714. * The color emitted from the material.
  45715. */
  45716. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45717. /**
  45718. * AKA Glossiness in other nomenclature.
  45719. */
  45720. _this.microSurface = 1.0;
  45721. /**
  45722. * source material index of refraction (IOR)' / 'destination material IOR.
  45723. */
  45724. _this.indexOfRefraction = 0.66;
  45725. /**
  45726. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45727. */
  45728. _this.invertRefractionY = false;
  45729. /**
  45730. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45731. * Materials half opaque for instance using refraction could benefit from this control.
  45732. */
  45733. _this.linkRefractionWithTransparency = false;
  45734. _this.useLightmapAsShadowmap = false;
  45735. /**
  45736. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45737. */
  45738. _this.useAlphaFromAlbedoTexture = false;
  45739. /**
  45740. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45741. */
  45742. _this.forceAlphaTest = false;
  45743. /**
  45744. * Defines the alpha limits in alpha test mode.
  45745. */
  45746. _this.alphaCutOff = 0.4;
  45747. /**
  45748. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45749. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45750. */
  45751. _this.useSpecularOverAlpha = true;
  45752. /**
  45753. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45754. */
  45755. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45756. /**
  45757. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45758. */
  45759. _this.useRoughnessFromMetallicTextureAlpha = true;
  45760. /**
  45761. * Specifies if the metallic texture contains the roughness information in its green channel.
  45762. */
  45763. _this.useRoughnessFromMetallicTextureGreen = false;
  45764. /**
  45765. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45766. */
  45767. _this.useMetallnessFromMetallicTextureBlue = false;
  45768. /**
  45769. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45770. */
  45771. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45772. /**
  45773. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45774. */
  45775. _this.useAmbientInGrayScale = false;
  45776. /**
  45777. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45778. * The material will try to infer what glossiness each pixel should be.
  45779. */
  45780. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45781. /**
  45782. * BJS is using an harcoded light falloff based on a manually sets up range.
  45783. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45784. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45785. */
  45786. _this.usePhysicalLightFalloff = true;
  45787. /**
  45788. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45789. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45790. */
  45791. _this.useRadianceOverAlpha = true;
  45792. /**
  45793. * Allows using an object space normal map (instead of tangent space).
  45794. */
  45795. _this.useObjectSpaceNormalMap = false;
  45796. /**
  45797. * Allows using the bump map in parallax mode.
  45798. */
  45799. _this.useParallax = false;
  45800. /**
  45801. * Allows using the bump map in parallax occlusion mode.
  45802. */
  45803. _this.useParallaxOcclusion = false;
  45804. /**
  45805. * Controls the scale bias of the parallax mode.
  45806. */
  45807. _this.parallaxScaleBias = 0.05;
  45808. /**
  45809. * If sets to true, disables all the lights affecting the material.
  45810. */
  45811. _this.disableLighting = false;
  45812. /**
  45813. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45814. */
  45815. _this.forceIrradianceInFragment = false;
  45816. /**
  45817. * Number of Simultaneous lights allowed on the material.
  45818. */
  45819. _this.maxSimultaneousLights = 4;
  45820. /**
  45821. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45822. */
  45823. _this.invertNormalMapX = false;
  45824. /**
  45825. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45826. */
  45827. _this.invertNormalMapY = false;
  45828. /**
  45829. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45830. */
  45831. _this.twoSidedLighting = false;
  45832. /**
  45833. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45834. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45835. */
  45836. _this.useAlphaFresnel = false;
  45837. /**
  45838. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45839. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45840. */
  45841. _this.useLinearAlphaFresnel = false;
  45842. /**
  45843. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45844. * And/Or occlude the blended part.
  45845. */
  45846. _this.environmentBRDFTexture = null;
  45847. /**
  45848. * Force normal to face away from face.
  45849. */
  45850. _this.forceNormalForward = false;
  45851. /**
  45852. * Enables specular anti aliasing in the PBR shader.
  45853. * It will both interacts on the Geometry for analytical and IBL lighting.
  45854. * It also prefilter the roughness map based on the bump values.
  45855. */
  45856. _this.enableSpecularAntiAliasing = false;
  45857. /**
  45858. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45859. * makes the reflect vector face the model (under horizon).
  45860. */
  45861. _this.useHorizonOcclusion = true;
  45862. /**
  45863. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45864. * too much the area relying on ambient texture to define their ambient occlusion.
  45865. */
  45866. _this.useRadianceOcclusion = true;
  45867. /**
  45868. * If set to true, no lighting calculations will be applied.
  45869. */
  45870. _this.unlit = false;
  45871. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45872. return _this;
  45873. }
  45874. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45875. /**
  45876. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45877. */
  45878. get: function () {
  45879. return this._PBRMATERIAL_OPAQUE;
  45880. },
  45881. enumerable: true,
  45882. configurable: true
  45883. });
  45884. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45885. /**
  45886. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45887. */
  45888. get: function () {
  45889. return this._PBRMATERIAL_ALPHATEST;
  45890. },
  45891. enumerable: true,
  45892. configurable: true
  45893. });
  45894. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45895. /**
  45896. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45897. */
  45898. get: function () {
  45899. return this._PBRMATERIAL_ALPHABLEND;
  45900. },
  45901. enumerable: true,
  45902. configurable: true
  45903. });
  45904. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45905. /**
  45906. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45907. * They are also discarded below the alpha cutoff threshold to improve performances.
  45908. */
  45909. get: function () {
  45910. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45911. },
  45912. enumerable: true,
  45913. configurable: true
  45914. });
  45915. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45916. /**
  45917. * Gets the image processing configuration used either in this material.
  45918. */
  45919. get: function () {
  45920. return this._imageProcessingConfiguration;
  45921. },
  45922. /**
  45923. * Sets the Default image processing configuration used either in the this material.
  45924. *
  45925. * If sets to null, the scene one is in use.
  45926. */
  45927. set: function (value) {
  45928. this._attachImageProcessingConfiguration(value);
  45929. // Ensure the effect will be rebuilt.
  45930. this._markAllSubMeshesAsTexturesDirty();
  45931. },
  45932. enumerable: true,
  45933. configurable: true
  45934. });
  45935. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45936. /**
  45937. * Gets wether the color curves effect is enabled.
  45938. */
  45939. get: function () {
  45940. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45941. },
  45942. /**
  45943. * Sets wether the color curves effect is enabled.
  45944. */
  45945. set: function (value) {
  45946. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45947. },
  45948. enumerable: true,
  45949. configurable: true
  45950. });
  45951. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45952. /**
  45953. * Gets wether the color grading effect is enabled.
  45954. */
  45955. get: function () {
  45956. return this.imageProcessingConfiguration.colorGradingEnabled;
  45957. },
  45958. /**
  45959. * Gets wether the color grading effect is enabled.
  45960. */
  45961. set: function (value) {
  45962. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45963. },
  45964. enumerable: true,
  45965. configurable: true
  45966. });
  45967. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45968. /**
  45969. * Gets wether tonemapping is enabled or not.
  45970. */
  45971. get: function () {
  45972. return this._imageProcessingConfiguration.toneMappingEnabled;
  45973. },
  45974. /**
  45975. * Sets wether tonemapping is enabled or not
  45976. */
  45977. set: function (value) {
  45978. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. ;
  45984. ;
  45985. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45986. /**
  45987. * The camera exposure used on this material.
  45988. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45989. * This corresponds to a photographic exposure.
  45990. */
  45991. get: function () {
  45992. return this._imageProcessingConfiguration.exposure;
  45993. },
  45994. /**
  45995. * The camera exposure used on this material.
  45996. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45997. * This corresponds to a photographic exposure.
  45998. */
  45999. set: function (value) {
  46000. this._imageProcessingConfiguration.exposure = value;
  46001. },
  46002. enumerable: true,
  46003. configurable: true
  46004. });
  46005. ;
  46006. ;
  46007. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46008. /**
  46009. * Gets The camera contrast used on this material.
  46010. */
  46011. get: function () {
  46012. return this._imageProcessingConfiguration.contrast;
  46013. },
  46014. /**
  46015. * Sets The camera contrast used on this material.
  46016. */
  46017. set: function (value) {
  46018. this._imageProcessingConfiguration.contrast = value;
  46019. },
  46020. enumerable: true,
  46021. configurable: true
  46022. });
  46023. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46024. /**
  46025. * Gets the Color Grading 2D Lookup Texture.
  46026. */
  46027. get: function () {
  46028. return this._imageProcessingConfiguration.colorGradingTexture;
  46029. },
  46030. /**
  46031. * Sets the Color Grading 2D Lookup Texture.
  46032. */
  46033. set: function (value) {
  46034. this._imageProcessingConfiguration.colorGradingTexture = value;
  46035. },
  46036. enumerable: true,
  46037. configurable: true
  46038. });
  46039. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46040. /**
  46041. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46042. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46043. * 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;
  46044. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46045. */
  46046. get: function () {
  46047. return this._imageProcessingConfiguration.colorCurves;
  46048. },
  46049. /**
  46050. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46051. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46052. * 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;
  46053. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46054. */
  46055. set: function (value) {
  46056. this._imageProcessingConfiguration.colorCurves = value;
  46057. },
  46058. enumerable: true,
  46059. configurable: true
  46060. });
  46061. /**
  46062. * Returns the name of this material class.
  46063. */
  46064. PBRMaterial.prototype.getClassName = function () {
  46065. return "PBRMaterial";
  46066. };
  46067. /**
  46068. * Returns an array of the actively used textures.
  46069. * @returns - Array of BaseTextures
  46070. */
  46071. PBRMaterial.prototype.getActiveTextures = function () {
  46072. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46073. if (this._albedoTexture) {
  46074. activeTextures.push(this._albedoTexture);
  46075. }
  46076. if (this._ambientTexture) {
  46077. activeTextures.push(this._ambientTexture);
  46078. }
  46079. if (this._opacityTexture) {
  46080. activeTextures.push(this._opacityTexture);
  46081. }
  46082. if (this._reflectionTexture) {
  46083. activeTextures.push(this._reflectionTexture);
  46084. }
  46085. if (this._emissiveTexture) {
  46086. activeTextures.push(this._emissiveTexture);
  46087. }
  46088. if (this._reflectivityTexture) {
  46089. activeTextures.push(this._reflectivityTexture);
  46090. }
  46091. if (this._metallicTexture) {
  46092. activeTextures.push(this._metallicTexture);
  46093. }
  46094. if (this._microSurfaceTexture) {
  46095. activeTextures.push(this._microSurfaceTexture);
  46096. }
  46097. if (this._bumpTexture) {
  46098. activeTextures.push(this._bumpTexture);
  46099. }
  46100. if (this._lightmapTexture) {
  46101. activeTextures.push(this._lightmapTexture);
  46102. }
  46103. if (this._refractionTexture) {
  46104. activeTextures.push(this._refractionTexture);
  46105. }
  46106. return activeTextures;
  46107. };
  46108. /**
  46109. * Checks to see if a texture is used in the material.
  46110. * @param texture - Base texture to use.
  46111. * @returns - Boolean specifying if a texture is used in the material.
  46112. */
  46113. PBRMaterial.prototype.hasTexture = function (texture) {
  46114. if (_super.prototype.hasTexture.call(this, texture)) {
  46115. return true;
  46116. }
  46117. if (this._albedoTexture === texture) {
  46118. return true;
  46119. }
  46120. if (this._ambientTexture === texture) {
  46121. return true;
  46122. }
  46123. if (this._opacityTexture === texture) {
  46124. return true;
  46125. }
  46126. if (this._reflectionTexture === texture) {
  46127. return true;
  46128. }
  46129. if (this._reflectivityTexture === texture) {
  46130. return true;
  46131. }
  46132. if (this._metallicTexture === texture) {
  46133. return true;
  46134. }
  46135. if (this._microSurfaceTexture === texture) {
  46136. return true;
  46137. }
  46138. if (this._bumpTexture === texture) {
  46139. return true;
  46140. }
  46141. if (this._lightmapTexture === texture) {
  46142. return true;
  46143. }
  46144. if (this._refractionTexture === texture) {
  46145. return true;
  46146. }
  46147. return false;
  46148. };
  46149. /**
  46150. * Makes a duplicate of the current material.
  46151. * @param name - name to use for the new material.
  46152. */
  46153. PBRMaterial.prototype.clone = function (name) {
  46154. var _this = this;
  46155. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46156. clone.id = name;
  46157. clone.name = name;
  46158. return clone;
  46159. };
  46160. /**
  46161. * Serializes this PBR Material.
  46162. * @returns - An object with the serialized material.
  46163. */
  46164. PBRMaterial.prototype.serialize = function () {
  46165. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46166. serializationObject.customType = "BABYLON.PBRMaterial";
  46167. return serializationObject;
  46168. };
  46169. // Statics
  46170. /**
  46171. * Parses a PBR Material from a serialized object.
  46172. * @param source - Serialized object.
  46173. * @param scene - BJS scene instance.
  46174. * @param rootUrl - url for the scene object
  46175. * @returns - PBRMaterial
  46176. */
  46177. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46178. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46179. };
  46180. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46181. /**
  46182. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46183. */
  46184. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46185. /**
  46186. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46187. */
  46188. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46189. /**
  46190. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46191. * They are also discarded below the alpha cutoff threshold to improve performances.
  46192. */
  46193. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46194. __decorate([
  46195. BABYLON.serialize(),
  46196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46197. ], PBRMaterial.prototype, "directIntensity", void 0);
  46198. __decorate([
  46199. BABYLON.serialize(),
  46200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46201. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46202. __decorate([
  46203. BABYLON.serialize(),
  46204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46205. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46206. __decorate([
  46207. BABYLON.serialize(),
  46208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46209. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46210. __decorate([
  46211. BABYLON.serialize(),
  46212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46213. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46214. __decorate([
  46215. BABYLON.serializeAsTexture(),
  46216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46217. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46218. __decorate([
  46219. BABYLON.serializeAsTexture(),
  46220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46221. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46222. __decorate([
  46223. BABYLON.serialize(),
  46224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46225. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46226. __decorate([
  46227. BABYLON.serializeAsTexture(),
  46228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46229. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46230. __decorate([
  46231. BABYLON.serializeAsTexture(),
  46232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46233. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46234. __decorate([
  46235. BABYLON.serializeAsTexture(),
  46236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46237. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46238. __decorate([
  46239. BABYLON.serializeAsTexture(),
  46240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46241. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46242. __decorate([
  46243. BABYLON.serializeAsTexture(),
  46244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46245. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46246. __decorate([
  46247. BABYLON.serialize(),
  46248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46249. ], PBRMaterial.prototype, "metallic", void 0);
  46250. __decorate([
  46251. BABYLON.serialize(),
  46252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46253. ], PBRMaterial.prototype, "roughness", void 0);
  46254. __decorate([
  46255. BABYLON.serializeAsTexture(),
  46256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46257. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46258. __decorate([
  46259. BABYLON.serializeAsTexture(),
  46260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46261. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46262. __decorate([
  46263. BABYLON.serializeAsTexture(),
  46264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46265. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46266. __decorate([
  46267. BABYLON.serializeAsTexture(),
  46268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46269. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46270. __decorate([
  46271. BABYLON.serializeAsColor3("ambient"),
  46272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46273. ], PBRMaterial.prototype, "ambientColor", void 0);
  46274. __decorate([
  46275. BABYLON.serializeAsColor3("albedo"),
  46276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46277. ], PBRMaterial.prototype, "albedoColor", void 0);
  46278. __decorate([
  46279. BABYLON.serializeAsColor3("reflectivity"),
  46280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46281. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46282. __decorate([
  46283. BABYLON.serializeAsColor3("reflection"),
  46284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46285. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46286. __decorate([
  46287. BABYLON.serializeAsColor3("emissive"),
  46288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46289. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46290. __decorate([
  46291. BABYLON.serialize(),
  46292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46293. ], PBRMaterial.prototype, "microSurface", void 0);
  46294. __decorate([
  46295. BABYLON.serialize(),
  46296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46297. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46298. __decorate([
  46299. BABYLON.serialize(),
  46300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46301. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46302. __decorate([
  46303. BABYLON.serialize(),
  46304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46305. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46306. __decorate([
  46307. BABYLON.serialize(),
  46308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46309. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46310. __decorate([
  46311. BABYLON.serialize(),
  46312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46313. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46314. __decorate([
  46315. BABYLON.serialize(),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46317. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46318. __decorate([
  46319. BABYLON.serialize(),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46321. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46322. __decorate([
  46323. BABYLON.serialize(),
  46324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46325. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46326. __decorate([
  46327. BABYLON.serialize(),
  46328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46329. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46330. __decorate([
  46331. BABYLON.serialize(),
  46332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46333. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46334. __decorate([
  46335. BABYLON.serialize(),
  46336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46337. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46338. __decorate([
  46339. BABYLON.serialize(),
  46340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46341. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46342. __decorate([
  46343. BABYLON.serialize(),
  46344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46345. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46346. __decorate([
  46347. BABYLON.serialize(),
  46348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46349. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46350. __decorate([
  46351. BABYLON.serialize(),
  46352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46353. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46354. __decorate([
  46355. BABYLON.serialize(),
  46356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46357. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46358. __decorate([
  46359. BABYLON.serialize(),
  46360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46361. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46362. __decorate([
  46363. BABYLON.serialize(),
  46364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46365. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46366. __decorate([
  46367. BABYLON.serialize(),
  46368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46369. ], PBRMaterial.prototype, "useParallax", void 0);
  46370. __decorate([
  46371. BABYLON.serialize(),
  46372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46373. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46374. __decorate([
  46375. BABYLON.serialize(),
  46376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46377. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46378. __decorate([
  46379. BABYLON.serialize(),
  46380. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46381. ], PBRMaterial.prototype, "disableLighting", void 0);
  46382. __decorate([
  46383. BABYLON.serialize(),
  46384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46385. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46386. __decorate([
  46387. BABYLON.serialize(),
  46388. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46389. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46390. __decorate([
  46391. BABYLON.serialize(),
  46392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46393. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46394. __decorate([
  46395. BABYLON.serialize(),
  46396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46397. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46398. __decorate([
  46399. BABYLON.serialize(),
  46400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46401. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46402. __decorate([
  46403. BABYLON.serialize(),
  46404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46405. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46406. __decorate([
  46407. BABYLON.serialize(),
  46408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46409. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46410. __decorate([
  46411. BABYLON.serializeAsTexture(),
  46412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46413. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46414. __decorate([
  46415. BABYLON.serialize(),
  46416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46417. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46418. __decorate([
  46419. BABYLON.serialize(),
  46420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46421. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46422. __decorate([
  46423. BABYLON.serialize(),
  46424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46425. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46426. __decorate([
  46427. BABYLON.serialize(),
  46428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46429. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46430. __decorate([
  46431. BABYLON.serialize(),
  46432. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46433. ], PBRMaterial.prototype, "unlit", void 0);
  46434. return PBRMaterial;
  46435. }(BABYLON.PBRBaseMaterial));
  46436. BABYLON.PBRMaterial = PBRMaterial;
  46437. })(BABYLON || (BABYLON = {}));
  46438. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46439. var BABYLON;
  46440. (function (BABYLON) {
  46441. /**
  46442. * The PBR material of BJS following the metal roughness convention.
  46443. *
  46444. * This fits to the PBR convention in the GLTF definition:
  46445. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46446. */
  46447. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46448. __extends(PBRMetallicRoughnessMaterial, _super);
  46449. /**
  46450. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46451. *
  46452. * @param name The material name
  46453. * @param scene The scene the material will be use in.
  46454. */
  46455. function PBRMetallicRoughnessMaterial(name, scene) {
  46456. var _this = _super.call(this, name, scene) || this;
  46457. _this._useRoughnessFromMetallicTextureAlpha = false;
  46458. _this._useRoughnessFromMetallicTextureGreen = true;
  46459. _this._useMetallnessFromMetallicTextureBlue = true;
  46460. _this.metallic = 1.0;
  46461. _this.roughness = 1.0;
  46462. return _this;
  46463. }
  46464. /**
  46465. * Return the currrent class name of the material.
  46466. */
  46467. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46468. return "PBRMetallicRoughnessMaterial";
  46469. };
  46470. /**
  46471. * Return the active textures of the material.
  46472. */
  46473. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46474. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46475. if (this.baseTexture) {
  46476. activeTextures.push(this.baseTexture);
  46477. }
  46478. if (this.metallicRoughnessTexture) {
  46479. activeTextures.push(this.metallicRoughnessTexture);
  46480. }
  46481. return activeTextures;
  46482. };
  46483. /**
  46484. * Checks to see if a texture is used in the material.
  46485. * @param texture - Base texture to use.
  46486. * @returns - Boolean specifying if a texture is used in the material.
  46487. */
  46488. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46489. if (_super.prototype.hasTexture.call(this, texture)) {
  46490. return true;
  46491. }
  46492. if (this.baseTexture === texture) {
  46493. return true;
  46494. }
  46495. if (this.metallicRoughnessTexture === texture) {
  46496. return true;
  46497. }
  46498. return false;
  46499. };
  46500. /**
  46501. * Makes a duplicate of the current material.
  46502. * @param name - name to use for the new material.
  46503. */
  46504. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46505. var _this = this;
  46506. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46507. clone.id = name;
  46508. clone.name = name;
  46509. return clone;
  46510. };
  46511. /**
  46512. * Serialize the material to a parsable JSON object.
  46513. */
  46514. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46516. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46517. return serializationObject;
  46518. };
  46519. /**
  46520. * Parses a JSON object correponding to the serialize function.
  46521. */
  46522. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46523. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46524. };
  46525. __decorate([
  46526. BABYLON.serializeAsColor3(),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46528. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46529. __decorate([
  46530. BABYLON.serializeAsTexture(),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46532. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46533. __decorate([
  46534. BABYLON.serialize(),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46536. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46537. __decorate([
  46538. BABYLON.serialize(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46540. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46541. __decorate([
  46542. BABYLON.serializeAsTexture(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46544. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46545. return PBRMetallicRoughnessMaterial;
  46546. }(BABYLON.PBRBaseSimpleMaterial));
  46547. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46548. })(BABYLON || (BABYLON = {}));
  46549. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46550. var BABYLON;
  46551. (function (BABYLON) {
  46552. /**
  46553. * The PBR material of BJS following the specular glossiness convention.
  46554. *
  46555. * This fits to the PBR convention in the GLTF definition:
  46556. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46557. */
  46558. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46559. __extends(PBRSpecularGlossinessMaterial, _super);
  46560. /**
  46561. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46562. *
  46563. * @param name The material name
  46564. * @param scene The scene the material will be use in.
  46565. */
  46566. function PBRSpecularGlossinessMaterial(name, scene) {
  46567. var _this = _super.call(this, name, scene) || this;
  46568. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46569. return _this;
  46570. }
  46571. /**
  46572. * Return the currrent class name of the material.
  46573. */
  46574. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46575. return "PBRSpecularGlossinessMaterial";
  46576. };
  46577. /**
  46578. * Return the active textures of the material.
  46579. */
  46580. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46581. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46582. if (this.diffuseTexture) {
  46583. activeTextures.push(this.diffuseTexture);
  46584. }
  46585. if (this.specularGlossinessTexture) {
  46586. activeTextures.push(this.specularGlossinessTexture);
  46587. }
  46588. return activeTextures;
  46589. };
  46590. /**
  46591. * Checks to see if a texture is used in the material.
  46592. * @param texture - Base texture to use.
  46593. * @returns - Boolean specifying if a texture is used in the material.
  46594. */
  46595. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46596. if (_super.prototype.hasTexture.call(this, texture)) {
  46597. return true;
  46598. }
  46599. if (this.diffuseTexture === texture) {
  46600. return true;
  46601. }
  46602. if (this.specularGlossinessTexture === texture) {
  46603. return true;
  46604. }
  46605. return false;
  46606. };
  46607. /**
  46608. * Makes a duplicate of the current material.
  46609. * @param name - name to use for the new material.
  46610. */
  46611. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46612. var _this = this;
  46613. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46614. clone.id = name;
  46615. clone.name = name;
  46616. return clone;
  46617. };
  46618. /**
  46619. * Serialize the material to a parsable JSON object.
  46620. */
  46621. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46622. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46623. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46624. return serializationObject;
  46625. };
  46626. /**
  46627. * Parses a JSON object correponding to the serialize function.
  46628. */
  46629. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46630. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46631. };
  46632. __decorate([
  46633. BABYLON.serializeAsColor3("diffuse"),
  46634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46635. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46636. __decorate([
  46637. BABYLON.serializeAsTexture(),
  46638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46639. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46640. __decorate([
  46641. BABYLON.serializeAsColor3("specular"),
  46642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46643. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46644. __decorate([
  46645. BABYLON.serialize(),
  46646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46647. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46648. __decorate([
  46649. BABYLON.serializeAsTexture(),
  46650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46651. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46652. return PBRSpecularGlossinessMaterial;
  46653. }(BABYLON.PBRBaseSimpleMaterial));
  46654. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46655. })(BABYLON || (BABYLON = {}));
  46656. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46657. var BABYLON;
  46658. (function (BABYLON) {
  46659. BABYLON.CameraInputTypes = {};
  46660. var CameraInputsManager = /** @class */ (function () {
  46661. function CameraInputsManager(camera) {
  46662. this.attached = {};
  46663. this.camera = camera;
  46664. this.checkInputs = function () { };
  46665. }
  46666. /**
  46667. * Add an input method to a camera.
  46668. * builtin inputs example: camera.inputs.addGamepad();
  46669. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46670. * @param input camera input method
  46671. */
  46672. CameraInputsManager.prototype.add = function (input) {
  46673. var type = input.getSimpleName();
  46674. if (this.attached[type]) {
  46675. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46676. return;
  46677. }
  46678. this.attached[type] = input;
  46679. input.camera = this.camera;
  46680. //for checkInputs, we are dynamically creating a function
  46681. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46682. if (input.checkInputs) {
  46683. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46684. }
  46685. if (this.attachedElement) {
  46686. input.attachControl(this.attachedElement);
  46687. }
  46688. };
  46689. /**
  46690. * Remove a specific input method from a camera
  46691. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46692. * @param inputToRemove camera input method
  46693. */
  46694. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46695. for (var cam in this.attached) {
  46696. var input = this.attached[cam];
  46697. if (input === inputToRemove) {
  46698. input.detachControl(this.attachedElement);
  46699. input.camera = null;
  46700. delete this.attached[cam];
  46701. this.rebuildInputCheck();
  46702. }
  46703. }
  46704. };
  46705. CameraInputsManager.prototype.removeByType = function (inputType) {
  46706. for (var cam in this.attached) {
  46707. var input = this.attached[cam];
  46708. if (input.getClassName() === inputType) {
  46709. input.detachControl(this.attachedElement);
  46710. input.camera = null;
  46711. delete this.attached[cam];
  46712. this.rebuildInputCheck();
  46713. }
  46714. }
  46715. };
  46716. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46717. var current = this.checkInputs;
  46718. return function () {
  46719. current();
  46720. fn();
  46721. };
  46722. };
  46723. CameraInputsManager.prototype.attachInput = function (input) {
  46724. if (this.attachedElement) {
  46725. input.attachControl(this.attachedElement, this.noPreventDefault);
  46726. }
  46727. };
  46728. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46729. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46730. if (this.attachedElement) {
  46731. return;
  46732. }
  46733. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46734. this.attachedElement = element;
  46735. this.noPreventDefault = noPreventDefault;
  46736. for (var cam in this.attached) {
  46737. this.attached[cam].attachControl(element, noPreventDefault);
  46738. }
  46739. };
  46740. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46741. if (disconnect === void 0) { disconnect = false; }
  46742. if (this.attachedElement !== element) {
  46743. return;
  46744. }
  46745. for (var cam in this.attached) {
  46746. this.attached[cam].detachControl(element);
  46747. if (disconnect) {
  46748. this.attached[cam].camera = null;
  46749. }
  46750. }
  46751. this.attachedElement = null;
  46752. };
  46753. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46754. this.checkInputs = function () { };
  46755. for (var cam in this.attached) {
  46756. var input = this.attached[cam];
  46757. if (input.checkInputs) {
  46758. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46759. }
  46760. }
  46761. };
  46762. /**
  46763. * Remove all attached input methods from a camera
  46764. */
  46765. CameraInputsManager.prototype.clear = function () {
  46766. if (this.attachedElement) {
  46767. this.detachElement(this.attachedElement, true);
  46768. }
  46769. this.attached = {};
  46770. this.attachedElement = null;
  46771. this.checkInputs = function () { };
  46772. };
  46773. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46774. var inputs = {};
  46775. for (var cam in this.attached) {
  46776. var input = this.attached[cam];
  46777. var res = BABYLON.SerializationHelper.Serialize(input);
  46778. inputs[input.getClassName()] = res;
  46779. }
  46780. serializedCamera.inputsmgr = inputs;
  46781. };
  46782. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46783. var parsedInputs = parsedCamera.inputsmgr;
  46784. if (parsedInputs) {
  46785. this.clear();
  46786. for (var n in parsedInputs) {
  46787. var construct = BABYLON.CameraInputTypes[n];
  46788. if (construct) {
  46789. var parsedinput = parsedInputs[n];
  46790. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46791. this.add(input);
  46792. }
  46793. }
  46794. }
  46795. else {
  46796. //2016-03-08 this part is for managing backward compatibility
  46797. for (var n in this.attached) {
  46798. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46799. if (construct) {
  46800. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46801. this.remove(this.attached[n]);
  46802. this.add(input);
  46803. }
  46804. }
  46805. }
  46806. };
  46807. return CameraInputsManager;
  46808. }());
  46809. BABYLON.CameraInputsManager = CameraInputsManager;
  46810. })(BABYLON || (BABYLON = {}));
  46811. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46812. var BABYLON;
  46813. (function (BABYLON) {
  46814. var TargetCamera = /** @class */ (function (_super) {
  46815. __extends(TargetCamera, _super);
  46816. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46817. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46818. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46819. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46820. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46821. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46822. _this.speed = 2.0;
  46823. _this.noRotationConstraint = false;
  46824. _this.lockedTarget = null;
  46825. _this._currentTarget = BABYLON.Vector3.Zero();
  46826. _this._viewMatrix = BABYLON.Matrix.Zero();
  46827. _this._camMatrix = BABYLON.Matrix.Zero();
  46828. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46829. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46830. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46831. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46832. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46833. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46834. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46835. return _this;
  46836. }
  46837. TargetCamera.prototype.getFrontPosition = function (distance) {
  46838. this.getWorldMatrix();
  46839. var direction = this.getTarget().subtract(this.position);
  46840. direction.normalize();
  46841. direction.scaleInPlace(distance);
  46842. return this.globalPosition.add(direction);
  46843. };
  46844. TargetCamera.prototype._getLockedTargetPosition = function () {
  46845. if (!this.lockedTarget) {
  46846. return null;
  46847. }
  46848. if (this.lockedTarget.absolutePosition) {
  46849. this.lockedTarget.computeWorldMatrix();
  46850. }
  46851. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46852. };
  46853. TargetCamera.prototype.storeState = function () {
  46854. this._storedPosition = this.position.clone();
  46855. this._storedRotation = this.rotation.clone();
  46856. if (this.rotationQuaternion) {
  46857. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46858. }
  46859. return _super.prototype.storeState.call(this);
  46860. };
  46861. /**
  46862. * Restored camera state. You must call storeState() first
  46863. */
  46864. TargetCamera.prototype._restoreStateValues = function () {
  46865. if (!_super.prototype._restoreStateValues.call(this)) {
  46866. return false;
  46867. }
  46868. this.position = this._storedPosition.clone();
  46869. this.rotation = this._storedRotation.clone();
  46870. if (this.rotationQuaternion) {
  46871. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46872. }
  46873. this.cameraDirection.copyFromFloats(0, 0, 0);
  46874. this.cameraRotation.copyFromFloats(0, 0);
  46875. return true;
  46876. };
  46877. // Cache
  46878. TargetCamera.prototype._initCache = function () {
  46879. _super.prototype._initCache.call(this);
  46880. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46881. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46882. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46883. };
  46884. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46885. if (!ignoreParentClass) {
  46886. _super.prototype._updateCache.call(this);
  46887. }
  46888. var lockedTargetPosition = this._getLockedTargetPosition();
  46889. if (!lockedTargetPosition) {
  46890. this._cache.lockedTarget = null;
  46891. }
  46892. else {
  46893. if (!this._cache.lockedTarget) {
  46894. this._cache.lockedTarget = lockedTargetPosition.clone();
  46895. }
  46896. else {
  46897. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46898. }
  46899. }
  46900. this._cache.rotation.copyFrom(this.rotation);
  46901. if (this.rotationQuaternion)
  46902. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46903. };
  46904. // Synchronized
  46905. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46906. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46907. return false;
  46908. }
  46909. var lockedTargetPosition = this._getLockedTargetPosition();
  46910. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46911. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46912. };
  46913. // Methods
  46914. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46915. var engine = this.getEngine();
  46916. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46917. };
  46918. // Target
  46919. TargetCamera.prototype.setTarget = function (target) {
  46920. this.upVector.normalize();
  46921. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46922. this._camMatrix.invert();
  46923. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46924. var vDir = target.subtract(this.position);
  46925. if (vDir.x >= 0.0) {
  46926. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46927. }
  46928. else {
  46929. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46930. }
  46931. this.rotation.z = 0;
  46932. if (isNaN(this.rotation.x)) {
  46933. this.rotation.x = 0;
  46934. }
  46935. if (isNaN(this.rotation.y)) {
  46936. this.rotation.y = 0;
  46937. }
  46938. if (isNaN(this.rotation.z)) {
  46939. this.rotation.z = 0;
  46940. }
  46941. if (this.rotationQuaternion) {
  46942. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46943. }
  46944. };
  46945. /**
  46946. * Return the current target position of the camera. This value is expressed in local space.
  46947. */
  46948. TargetCamera.prototype.getTarget = function () {
  46949. return this._currentTarget;
  46950. };
  46951. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46952. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46953. };
  46954. TargetCamera.prototype._updatePosition = function () {
  46955. if (this.parent) {
  46956. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46957. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46958. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46959. return;
  46960. }
  46961. this.position.addInPlace(this.cameraDirection);
  46962. };
  46963. TargetCamera.prototype._checkInputs = function () {
  46964. var needToMove = this._decideIfNeedsToMove();
  46965. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46966. // Move
  46967. if (needToMove) {
  46968. this._updatePosition();
  46969. }
  46970. // Rotate
  46971. if (needToRotate) {
  46972. this.rotation.x += this.cameraRotation.x;
  46973. this.rotation.y += this.cameraRotation.y;
  46974. //rotate, if quaternion is set and rotation was used
  46975. if (this.rotationQuaternion) {
  46976. var len = this.rotation.lengthSquared();
  46977. if (len) {
  46978. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46979. }
  46980. }
  46981. if (!this.noRotationConstraint) {
  46982. var limit = (Math.PI / 2) * 0.95;
  46983. if (this.rotation.x > limit)
  46984. this.rotation.x = limit;
  46985. if (this.rotation.x < -limit)
  46986. this.rotation.x = -limit;
  46987. }
  46988. }
  46989. // Inertia
  46990. if (needToMove) {
  46991. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46992. this.cameraDirection.x = 0;
  46993. }
  46994. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46995. this.cameraDirection.y = 0;
  46996. }
  46997. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46998. this.cameraDirection.z = 0;
  46999. }
  47000. this.cameraDirection.scaleInPlace(this.inertia);
  47001. }
  47002. if (needToRotate) {
  47003. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47004. this.cameraRotation.x = 0;
  47005. }
  47006. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47007. this.cameraRotation.y = 0;
  47008. }
  47009. this.cameraRotation.scaleInPlace(this.inertia);
  47010. }
  47011. _super.prototype._checkInputs.call(this);
  47012. };
  47013. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47014. if (this.rotationQuaternion) {
  47015. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47016. }
  47017. else {
  47018. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47019. }
  47020. //update the up vector!
  47021. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47022. };
  47023. TargetCamera.prototype._getViewMatrix = function () {
  47024. if (this.lockedTarget) {
  47025. this.setTarget(this._getLockedTargetPosition());
  47026. }
  47027. // Compute
  47028. this._updateCameraRotationMatrix();
  47029. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47030. // Computing target and final matrix
  47031. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47032. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47033. return this._viewMatrix;
  47034. };
  47035. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47036. if (this.parent) {
  47037. var parentWorldMatrix = this.parent.getWorldMatrix();
  47038. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47039. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47040. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47041. this._markSyncedWithParent();
  47042. }
  47043. else {
  47044. this._globalPosition.copyFrom(this.position);
  47045. this._globalCurrentTarget.copyFrom(target);
  47046. this._globalCurrentUpVector.copyFrom(up);
  47047. }
  47048. if (this.getScene().useRightHandedSystem) {
  47049. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47050. }
  47051. else {
  47052. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47053. }
  47054. };
  47055. /**
  47056. * @override
  47057. * Override Camera.createRigCamera
  47058. */
  47059. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47060. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47061. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47062. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47063. if (!this.rotationQuaternion) {
  47064. this.rotationQuaternion = new BABYLON.Quaternion();
  47065. }
  47066. rigCamera._cameraRigParams = {};
  47067. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47068. }
  47069. return rigCamera;
  47070. }
  47071. return null;
  47072. };
  47073. /**
  47074. * @override
  47075. * Override Camera._updateRigCameras
  47076. */
  47077. TargetCamera.prototype._updateRigCameras = function () {
  47078. var camLeft = this._rigCameras[0];
  47079. var camRight = this._rigCameras[1];
  47080. switch (this.cameraRigMode) {
  47081. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47082. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47084. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47085. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47086. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47087. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47088. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47089. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47090. camLeft.setTarget(this.getTarget());
  47091. camRight.setTarget(this.getTarget());
  47092. break;
  47093. case BABYLON.Camera.RIG_MODE_VR:
  47094. if (camLeft.rotationQuaternion) {
  47095. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47096. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47097. }
  47098. else {
  47099. camLeft.rotation.copyFrom(this.rotation);
  47100. camRight.rotation.copyFrom(this.rotation);
  47101. }
  47102. camLeft.position.copyFrom(this.position);
  47103. camRight.position.copyFrom(this.position);
  47104. break;
  47105. }
  47106. _super.prototype._updateRigCameras.call(this);
  47107. };
  47108. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47109. if (!this._rigCamTransformMatrix) {
  47110. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47111. }
  47112. var target = this.getTarget();
  47113. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47114. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47115. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47116. };
  47117. TargetCamera.prototype.getClassName = function () {
  47118. return "TargetCamera";
  47119. };
  47120. __decorate([
  47121. BABYLON.serializeAsVector3()
  47122. ], TargetCamera.prototype, "rotation", void 0);
  47123. __decorate([
  47124. BABYLON.serialize()
  47125. ], TargetCamera.prototype, "speed", void 0);
  47126. __decorate([
  47127. BABYLON.serializeAsMeshReference("lockedTargetId")
  47128. ], TargetCamera.prototype, "lockedTarget", void 0);
  47129. return TargetCamera;
  47130. }(BABYLON.Camera));
  47131. BABYLON.TargetCamera = TargetCamera;
  47132. })(BABYLON || (BABYLON = {}));
  47133. //# sourceMappingURL=babylon.targetCamera.js.map
  47134. var BABYLON;
  47135. (function (BABYLON) {
  47136. var FreeCameraMouseInput = /** @class */ (function () {
  47137. function FreeCameraMouseInput(touchEnabled) {
  47138. if (touchEnabled === void 0) { touchEnabled = true; }
  47139. this.touchEnabled = touchEnabled;
  47140. this.buttons = [0, 1, 2];
  47141. this.angularSensibility = 2000.0;
  47142. this.previousPosition = null;
  47143. }
  47144. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47145. var _this = this;
  47146. var engine = this.camera.getEngine();
  47147. if (!this._pointerInput) {
  47148. this._pointerInput = function (p, s) {
  47149. var evt = p.event;
  47150. if (engine.isInVRExclusivePointerMode) {
  47151. return;
  47152. }
  47153. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47154. return;
  47155. }
  47156. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47157. return;
  47158. }
  47159. var srcElement = (evt.srcElement || evt.target);
  47160. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47161. try {
  47162. srcElement.setPointerCapture(evt.pointerId);
  47163. }
  47164. catch (e) {
  47165. //Nothing to do with the error. Execution will continue.
  47166. }
  47167. _this.previousPosition = {
  47168. x: evt.clientX,
  47169. y: evt.clientY
  47170. };
  47171. if (!noPreventDefault) {
  47172. evt.preventDefault();
  47173. element.focus();
  47174. }
  47175. }
  47176. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47177. try {
  47178. srcElement.releasePointerCapture(evt.pointerId);
  47179. }
  47180. catch (e) {
  47181. //Nothing to do with the error.
  47182. }
  47183. _this.previousPosition = null;
  47184. if (!noPreventDefault) {
  47185. evt.preventDefault();
  47186. }
  47187. }
  47188. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47189. if (!_this.previousPosition || engine.isPointerLock) {
  47190. return;
  47191. }
  47192. var offsetX = evt.clientX - _this.previousPosition.x;
  47193. if (_this.camera.getScene().useRightHandedSystem)
  47194. offsetX *= -1;
  47195. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47196. offsetX *= -1;
  47197. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47198. var offsetY = evt.clientY - _this.previousPosition.y;
  47199. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47200. _this.previousPosition = {
  47201. x: evt.clientX,
  47202. y: evt.clientY
  47203. };
  47204. if (!noPreventDefault) {
  47205. evt.preventDefault();
  47206. }
  47207. }
  47208. };
  47209. }
  47210. this._onMouseMove = function (evt) {
  47211. if (!engine.isPointerLock) {
  47212. return;
  47213. }
  47214. if (engine.isInVRExclusivePointerMode) {
  47215. return;
  47216. }
  47217. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47218. if (_this.camera.getScene().useRightHandedSystem)
  47219. offsetX *= -1;
  47220. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47221. offsetX *= -1;
  47222. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47223. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47224. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47225. _this.previousPosition = null;
  47226. if (!noPreventDefault) {
  47227. evt.preventDefault();
  47228. }
  47229. };
  47230. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47231. element.addEventListener("mousemove", this._onMouseMove, false);
  47232. };
  47233. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47234. if (this._observer && element) {
  47235. this.camera.getScene().onPointerObservable.remove(this._observer);
  47236. if (this._onMouseMove) {
  47237. element.removeEventListener("mousemove", this._onMouseMove);
  47238. }
  47239. this._observer = null;
  47240. this._onMouseMove = null;
  47241. this.previousPosition = null;
  47242. }
  47243. };
  47244. FreeCameraMouseInput.prototype.getClassName = function () {
  47245. return "FreeCameraMouseInput";
  47246. };
  47247. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47248. return "mouse";
  47249. };
  47250. __decorate([
  47251. BABYLON.serialize()
  47252. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47253. __decorate([
  47254. BABYLON.serialize()
  47255. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47256. return FreeCameraMouseInput;
  47257. }());
  47258. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47259. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47260. })(BABYLON || (BABYLON = {}));
  47261. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47262. var BABYLON;
  47263. (function (BABYLON) {
  47264. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47265. function FreeCameraKeyboardMoveInput() {
  47266. this._keys = new Array();
  47267. this.keysUp = [38];
  47268. this.keysDown = [40];
  47269. this.keysLeft = [37];
  47270. this.keysRight = [39];
  47271. }
  47272. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47273. var _this = this;
  47274. if (this._onCanvasBlurObserver) {
  47275. return;
  47276. }
  47277. this._scene = this.camera.getScene();
  47278. this._engine = this._scene.getEngine();
  47279. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47280. _this._keys = [];
  47281. });
  47282. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47283. var evt = info.event;
  47284. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47285. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47286. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47287. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47288. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47289. var index = _this._keys.indexOf(evt.keyCode);
  47290. if (index === -1) {
  47291. _this._keys.push(evt.keyCode);
  47292. }
  47293. if (!noPreventDefault) {
  47294. evt.preventDefault();
  47295. }
  47296. }
  47297. }
  47298. else {
  47299. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47300. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47301. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47302. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47303. var index = _this._keys.indexOf(evt.keyCode);
  47304. if (index >= 0) {
  47305. _this._keys.splice(index, 1);
  47306. }
  47307. if (!noPreventDefault) {
  47308. evt.preventDefault();
  47309. }
  47310. }
  47311. }
  47312. });
  47313. };
  47314. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47315. if (this._scene) {
  47316. if (this._onKeyboardObserver) {
  47317. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47318. }
  47319. if (this._onCanvasBlurObserver) {
  47320. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47321. }
  47322. this._onKeyboardObserver = null;
  47323. this._onCanvasBlurObserver = null;
  47324. }
  47325. this._keys = [];
  47326. };
  47327. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47328. if (this._onKeyboardObserver) {
  47329. var camera = this.camera;
  47330. // Keyboard
  47331. for (var index = 0; index < this._keys.length; index++) {
  47332. var keyCode = this._keys[index];
  47333. var speed = camera._computeLocalCameraSpeed();
  47334. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47335. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47336. }
  47337. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47338. camera._localDirection.copyFromFloats(0, 0, speed);
  47339. }
  47340. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47341. camera._localDirection.copyFromFloats(speed, 0, 0);
  47342. }
  47343. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47344. camera._localDirection.copyFromFloats(0, 0, -speed);
  47345. }
  47346. if (camera.getScene().useRightHandedSystem) {
  47347. camera._localDirection.z *= -1;
  47348. }
  47349. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47350. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47351. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47352. }
  47353. }
  47354. };
  47355. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47356. return "FreeCameraKeyboardMoveInput";
  47357. };
  47358. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47359. this._keys = [];
  47360. };
  47361. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47362. return "keyboard";
  47363. };
  47364. __decorate([
  47365. BABYLON.serialize()
  47366. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47367. __decorate([
  47368. BABYLON.serialize()
  47369. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47370. __decorate([
  47371. BABYLON.serialize()
  47372. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47373. __decorate([
  47374. BABYLON.serialize()
  47375. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47376. return FreeCameraKeyboardMoveInput;
  47377. }());
  47378. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47379. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47380. })(BABYLON || (BABYLON = {}));
  47381. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47382. var BABYLON;
  47383. (function (BABYLON) {
  47384. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47385. __extends(FreeCameraInputsManager, _super);
  47386. function FreeCameraInputsManager(camera) {
  47387. return _super.call(this, camera) || this;
  47388. }
  47389. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47390. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47391. return this;
  47392. };
  47393. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47394. if (touchEnabled === void 0) { touchEnabled = true; }
  47395. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47396. return this;
  47397. };
  47398. FreeCameraInputsManager.prototype.addGamepad = function () {
  47399. this.add(new BABYLON.FreeCameraGamepadInput());
  47400. return this;
  47401. };
  47402. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47403. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47404. return this;
  47405. };
  47406. FreeCameraInputsManager.prototype.addTouch = function () {
  47407. this.add(new BABYLON.FreeCameraTouchInput());
  47408. return this;
  47409. };
  47410. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47411. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47412. return this;
  47413. };
  47414. return FreeCameraInputsManager;
  47415. }(BABYLON.CameraInputsManager));
  47416. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47417. })(BABYLON || (BABYLON = {}));
  47418. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47419. var BABYLON;
  47420. (function (BABYLON) {
  47421. var FreeCamera = /** @class */ (function (_super) {
  47422. __extends(FreeCamera, _super);
  47423. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47424. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47425. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47426. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47427. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47428. _this.checkCollisions = false;
  47429. _this.applyGravity = false;
  47430. _this._needMoveForGravity = false;
  47431. _this._oldPosition = BABYLON.Vector3.Zero();
  47432. _this._diffPosition = BABYLON.Vector3.Zero();
  47433. _this._newPosition = BABYLON.Vector3.Zero();
  47434. // Collisions
  47435. _this._collisionMask = -1;
  47436. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47437. if (collidedMesh === void 0) { collidedMesh = null; }
  47438. //TODO move this to the collision coordinator!
  47439. if (_this.getScene().workerCollisions)
  47440. newPosition.multiplyInPlace(_this._collider._radius);
  47441. var updatePosition = function (newPos) {
  47442. _this._newPosition.copyFrom(newPos);
  47443. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47444. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47445. _this.position.addInPlace(_this._diffPosition);
  47446. if (_this.onCollide && collidedMesh) {
  47447. _this.onCollide(collidedMesh);
  47448. }
  47449. }
  47450. };
  47451. updatePosition(newPosition);
  47452. };
  47453. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47454. _this.inputs.addKeyboard().addMouse();
  47455. return _this;
  47456. }
  47457. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47458. //-- begin properties for backward compatibility for inputs
  47459. /**
  47460. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47461. * Higher values reduce sensitivity.
  47462. */
  47463. get: function () {
  47464. var mouse = this.inputs.attached["mouse"];
  47465. if (mouse)
  47466. return mouse.angularSensibility;
  47467. return 0;
  47468. },
  47469. /**
  47470. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47471. * Higher values reduce sensitivity.
  47472. */
  47473. set: function (value) {
  47474. var mouse = this.inputs.attached["mouse"];
  47475. if (mouse)
  47476. mouse.angularSensibility = value;
  47477. },
  47478. enumerable: true,
  47479. configurable: true
  47480. });
  47481. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47482. get: function () {
  47483. var keyboard = this.inputs.attached["keyboard"];
  47484. if (keyboard)
  47485. return keyboard.keysUp;
  47486. return [];
  47487. },
  47488. set: function (value) {
  47489. var keyboard = this.inputs.attached["keyboard"];
  47490. if (keyboard)
  47491. keyboard.keysUp = value;
  47492. },
  47493. enumerable: true,
  47494. configurable: true
  47495. });
  47496. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47497. get: function () {
  47498. var keyboard = this.inputs.attached["keyboard"];
  47499. if (keyboard)
  47500. return keyboard.keysDown;
  47501. return [];
  47502. },
  47503. set: function (value) {
  47504. var keyboard = this.inputs.attached["keyboard"];
  47505. if (keyboard)
  47506. keyboard.keysDown = value;
  47507. },
  47508. enumerable: true,
  47509. configurable: true
  47510. });
  47511. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47512. get: function () {
  47513. var keyboard = this.inputs.attached["keyboard"];
  47514. if (keyboard)
  47515. return keyboard.keysLeft;
  47516. return [];
  47517. },
  47518. set: function (value) {
  47519. var keyboard = this.inputs.attached["keyboard"];
  47520. if (keyboard)
  47521. keyboard.keysLeft = value;
  47522. },
  47523. enumerable: true,
  47524. configurable: true
  47525. });
  47526. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47527. get: function () {
  47528. var keyboard = this.inputs.attached["keyboard"];
  47529. if (keyboard)
  47530. return keyboard.keysRight;
  47531. return [];
  47532. },
  47533. set: function (value) {
  47534. var keyboard = this.inputs.attached["keyboard"];
  47535. if (keyboard)
  47536. keyboard.keysRight = value;
  47537. },
  47538. enumerable: true,
  47539. configurable: true
  47540. });
  47541. // Controls
  47542. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47543. this.inputs.attachElement(element, noPreventDefault);
  47544. };
  47545. FreeCamera.prototype.detachControl = function (element) {
  47546. this.inputs.detachElement(element);
  47547. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47548. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47549. };
  47550. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47551. get: function () {
  47552. return this._collisionMask;
  47553. },
  47554. set: function (mask) {
  47555. this._collisionMask = !isNaN(mask) ? mask : -1;
  47556. },
  47557. enumerable: true,
  47558. configurable: true
  47559. });
  47560. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47561. var globalPosition;
  47562. if (this.parent) {
  47563. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47564. }
  47565. else {
  47566. globalPosition = this.position;
  47567. }
  47568. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47569. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47570. if (!this._collider) {
  47571. this._collider = new BABYLON.Collider();
  47572. }
  47573. this._collider._radius = this.ellipsoid;
  47574. this._collider.collisionMask = this._collisionMask;
  47575. //no need for clone, as long as gravity is not on.
  47576. var actualDisplacement = displacement;
  47577. //add gravity to the direction to prevent the dual-collision checking
  47578. if (this.applyGravity) {
  47579. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47580. actualDisplacement = displacement.add(this.getScene().gravity);
  47581. }
  47582. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47583. };
  47584. FreeCamera.prototype._checkInputs = function () {
  47585. if (!this._localDirection) {
  47586. this._localDirection = BABYLON.Vector3.Zero();
  47587. this._transformedDirection = BABYLON.Vector3.Zero();
  47588. }
  47589. this.inputs.checkInputs();
  47590. _super.prototype._checkInputs.call(this);
  47591. };
  47592. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47593. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47594. };
  47595. FreeCamera.prototype._updatePosition = function () {
  47596. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47597. this._collideWithWorld(this.cameraDirection);
  47598. }
  47599. else {
  47600. _super.prototype._updatePosition.call(this);
  47601. }
  47602. };
  47603. FreeCamera.prototype.dispose = function () {
  47604. this.inputs.clear();
  47605. _super.prototype.dispose.call(this);
  47606. };
  47607. FreeCamera.prototype.getClassName = function () {
  47608. return "FreeCamera";
  47609. };
  47610. __decorate([
  47611. BABYLON.serializeAsVector3()
  47612. ], FreeCamera.prototype, "ellipsoid", void 0);
  47613. __decorate([
  47614. BABYLON.serializeAsVector3()
  47615. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47616. __decorate([
  47617. BABYLON.serialize()
  47618. ], FreeCamera.prototype, "checkCollisions", void 0);
  47619. __decorate([
  47620. BABYLON.serialize()
  47621. ], FreeCamera.prototype, "applyGravity", void 0);
  47622. return FreeCamera;
  47623. }(BABYLON.TargetCamera));
  47624. BABYLON.FreeCamera = FreeCamera;
  47625. })(BABYLON || (BABYLON = {}));
  47626. //# sourceMappingURL=babylon.freeCamera.js.map
  47627. var BABYLON;
  47628. (function (BABYLON) {
  47629. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47630. function ArcRotateCameraKeyboardMoveInput() {
  47631. this._keys = new Array();
  47632. this.keysUp = [38];
  47633. this.keysDown = [40];
  47634. this.keysLeft = [37];
  47635. this.keysRight = [39];
  47636. this.keysReset = [220];
  47637. this.panningSensibility = 50.0;
  47638. this.zoomingSensibility = 25.0;
  47639. this.useAltToZoom = true;
  47640. }
  47641. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47642. var _this = this;
  47643. if (this._onCanvasBlurObserver) {
  47644. return;
  47645. }
  47646. this._scene = this.camera.getScene();
  47647. this._engine = this._scene.getEngine();
  47648. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47649. _this._keys = [];
  47650. });
  47651. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47652. var evt = info.event;
  47653. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47654. _this._ctrlPressed = evt.ctrlKey;
  47655. _this._altPressed = evt.altKey;
  47656. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47657. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47658. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47659. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47660. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47661. var index = _this._keys.indexOf(evt.keyCode);
  47662. if (index === -1) {
  47663. _this._keys.push(evt.keyCode);
  47664. }
  47665. if (evt.preventDefault) {
  47666. if (!noPreventDefault) {
  47667. evt.preventDefault();
  47668. }
  47669. }
  47670. }
  47671. }
  47672. else {
  47673. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47674. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47675. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47676. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47677. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47678. var index = _this._keys.indexOf(evt.keyCode);
  47679. if (index >= 0) {
  47680. _this._keys.splice(index, 1);
  47681. }
  47682. if (evt.preventDefault) {
  47683. if (!noPreventDefault) {
  47684. evt.preventDefault();
  47685. }
  47686. }
  47687. }
  47688. }
  47689. });
  47690. };
  47691. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47692. if (this._scene) {
  47693. if (this._onKeyboardObserver) {
  47694. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47695. }
  47696. if (this._onCanvasBlurObserver) {
  47697. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47698. }
  47699. this._onKeyboardObserver = null;
  47700. this._onCanvasBlurObserver = null;
  47701. }
  47702. this._keys = [];
  47703. };
  47704. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47705. if (this._onKeyboardObserver) {
  47706. var camera = this.camera;
  47707. for (var index = 0; index < this._keys.length; index++) {
  47708. var keyCode = this._keys[index];
  47709. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47710. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47711. camera.inertialPanningX -= 1 / this.panningSensibility;
  47712. }
  47713. else {
  47714. camera.inertialAlphaOffset -= 0.01;
  47715. }
  47716. }
  47717. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47718. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47719. camera.inertialPanningY += 1 / this.panningSensibility;
  47720. }
  47721. else if (this._altPressed && this.useAltToZoom) {
  47722. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47723. }
  47724. else {
  47725. camera.inertialBetaOffset -= 0.01;
  47726. }
  47727. }
  47728. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47729. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47730. camera.inertialPanningX += 1 / this.panningSensibility;
  47731. }
  47732. else {
  47733. camera.inertialAlphaOffset += 0.01;
  47734. }
  47735. }
  47736. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47737. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47738. camera.inertialPanningY -= 1 / this.panningSensibility;
  47739. }
  47740. else if (this._altPressed && this.useAltToZoom) {
  47741. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47742. }
  47743. else {
  47744. camera.inertialBetaOffset += 0.01;
  47745. }
  47746. }
  47747. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47748. camera.restoreState();
  47749. }
  47750. }
  47751. }
  47752. };
  47753. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47754. return "ArcRotateCameraKeyboardMoveInput";
  47755. };
  47756. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47757. return "keyboard";
  47758. };
  47759. __decorate([
  47760. BABYLON.serialize()
  47761. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47762. __decorate([
  47763. BABYLON.serialize()
  47764. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47765. __decorate([
  47766. BABYLON.serialize()
  47767. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47768. __decorate([
  47769. BABYLON.serialize()
  47770. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47771. __decorate([
  47772. BABYLON.serialize()
  47773. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47774. __decorate([
  47775. BABYLON.serialize()
  47776. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47777. __decorate([
  47778. BABYLON.serialize()
  47779. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47780. __decorate([
  47781. BABYLON.serialize()
  47782. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47783. return ArcRotateCameraKeyboardMoveInput;
  47784. }());
  47785. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47786. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47787. })(BABYLON || (BABYLON = {}));
  47788. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47789. var BABYLON;
  47790. (function (BABYLON) {
  47791. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47792. function ArcRotateCameraMouseWheelInput() {
  47793. this.wheelPrecision = 3.0;
  47794. /**
  47795. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47796. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47797. */
  47798. this.wheelDeltaPercentage = 0;
  47799. }
  47800. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47801. var _this = this;
  47802. this._wheel = function (p, s) {
  47803. //sanity check - this should be a PointerWheel event.
  47804. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47805. return;
  47806. var event = p.event;
  47807. var delta = 0;
  47808. if (event.wheelDelta) {
  47809. if (_this.wheelDeltaPercentage) {
  47810. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47811. if (event.wheelDelta > 0) {
  47812. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47813. }
  47814. else {
  47815. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47816. }
  47817. }
  47818. else {
  47819. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47820. }
  47821. }
  47822. else if (event.detail) {
  47823. delta = -event.detail / _this.wheelPrecision;
  47824. }
  47825. if (delta)
  47826. _this.camera.inertialRadiusOffset += delta;
  47827. if (event.preventDefault) {
  47828. if (!noPreventDefault) {
  47829. event.preventDefault();
  47830. }
  47831. }
  47832. };
  47833. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47834. };
  47835. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47836. if (this._observer && element) {
  47837. this.camera.getScene().onPointerObservable.remove(this._observer);
  47838. this._observer = null;
  47839. this._wheel = null;
  47840. }
  47841. };
  47842. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47843. return "ArcRotateCameraMouseWheelInput";
  47844. };
  47845. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47846. return "mousewheel";
  47847. };
  47848. __decorate([
  47849. BABYLON.serialize()
  47850. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47851. __decorate([
  47852. BABYLON.serialize()
  47853. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47854. return ArcRotateCameraMouseWheelInput;
  47855. }());
  47856. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47857. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47858. })(BABYLON || (BABYLON = {}));
  47859. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47860. var BABYLON;
  47861. (function (BABYLON) {
  47862. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47863. function ArcRotateCameraPointersInput() {
  47864. this.buttons = [0, 1, 2];
  47865. this.angularSensibilityX = 1000.0;
  47866. this.angularSensibilityY = 1000.0;
  47867. this.pinchPrecision = 12.0;
  47868. /**
  47869. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47870. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47871. */
  47872. this.pinchDeltaPercentage = 0;
  47873. this.panningSensibility = 1000.0;
  47874. this.multiTouchPanning = true;
  47875. this.multiTouchPanAndZoom = true;
  47876. this._isPanClick = false;
  47877. this.pinchInwards = true;
  47878. }
  47879. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47880. var _this = this;
  47881. var engine = this.camera.getEngine();
  47882. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47883. var pointA = null;
  47884. var pointB = null;
  47885. var previousPinchSquaredDistance = 0;
  47886. var initialDistance = 0;
  47887. var twoFingerActivityCount = 0;
  47888. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47889. this._pointerInput = function (p, s) {
  47890. var evt = p.event;
  47891. var isTouch = p.event.pointerType === "touch";
  47892. if (engine.isInVRExclusivePointerMode) {
  47893. return;
  47894. }
  47895. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47896. return;
  47897. }
  47898. var srcElement = (evt.srcElement || evt.target);
  47899. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47900. try {
  47901. srcElement.setPointerCapture(evt.pointerId);
  47902. }
  47903. catch (e) {
  47904. //Nothing to do with the error. Execution will continue.
  47905. }
  47906. // Manage panning with pan button click
  47907. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47908. // manage pointers
  47909. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47910. if (pointA === null) {
  47911. pointA = cacheSoloPointer;
  47912. }
  47913. else if (pointB === null) {
  47914. pointB = cacheSoloPointer;
  47915. }
  47916. if (!noPreventDefault) {
  47917. evt.preventDefault();
  47918. element.focus();
  47919. }
  47920. }
  47921. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47922. _this.camera.restoreState();
  47923. }
  47924. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47925. try {
  47926. srcElement.releasePointerCapture(evt.pointerId);
  47927. }
  47928. catch (e) {
  47929. //Nothing to do with the error.
  47930. }
  47931. cacheSoloPointer = null;
  47932. previousPinchSquaredDistance = 0;
  47933. previousMultiTouchPanPosition.isPaning = false;
  47934. previousMultiTouchPanPosition.isPinching = false;
  47935. twoFingerActivityCount = 0;
  47936. initialDistance = 0;
  47937. if (!isTouch) {
  47938. pointB = null; // Mouse and pen are mono pointer
  47939. }
  47940. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47941. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47942. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47943. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47944. if (engine._badOS) {
  47945. pointA = pointB = null;
  47946. }
  47947. else {
  47948. //only remove the impacted pointer in case of multitouch allowing on most
  47949. //platforms switching from rotate to zoom and pan seamlessly.
  47950. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47951. pointA = pointB;
  47952. pointB = null;
  47953. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47954. }
  47955. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47956. pointB = null;
  47957. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47958. }
  47959. else {
  47960. pointA = pointB = null;
  47961. }
  47962. }
  47963. if (!noPreventDefault) {
  47964. evt.preventDefault();
  47965. }
  47966. }
  47967. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47968. if (!noPreventDefault) {
  47969. evt.preventDefault();
  47970. }
  47971. // One button down
  47972. if (pointA && pointB === null && cacheSoloPointer) {
  47973. if (_this.panningSensibility !== 0 &&
  47974. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47975. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47976. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47977. }
  47978. else {
  47979. var offsetX = evt.clientX - cacheSoloPointer.x;
  47980. var offsetY = evt.clientY - cacheSoloPointer.y;
  47981. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47982. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47983. }
  47984. cacheSoloPointer.x = evt.clientX;
  47985. cacheSoloPointer.y = evt.clientY;
  47986. }
  47987. // Two buttons down: pinch/pan
  47988. else if (pointA && pointB) {
  47989. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47990. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47991. ed.x = evt.clientX;
  47992. ed.y = evt.clientY;
  47993. var direction = _this.pinchInwards ? 1 : -1;
  47994. var distX = pointA.x - pointB.x;
  47995. var distY = pointA.y - pointB.y;
  47996. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47997. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47998. if (previousPinchSquaredDistance === 0) {
  47999. initialDistance = pinchDistance;
  48000. previousPinchSquaredDistance = pinchSquaredDistance;
  48001. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48002. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48003. return;
  48004. }
  48005. if (_this.multiTouchPanAndZoom) {
  48006. if (_this.pinchDeltaPercentage) {
  48007. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48008. }
  48009. else {
  48010. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48011. (_this.pinchPrecision *
  48012. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48013. direction);
  48014. }
  48015. if (_this.panningSensibility !== 0) {
  48016. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48017. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48018. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48019. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48020. previousMultiTouchPanPosition.x = pointersCenterX;
  48021. previousMultiTouchPanPosition.y = pointersCenterY;
  48022. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48023. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48024. }
  48025. }
  48026. else {
  48027. twoFingerActivityCount++;
  48028. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48029. if (_this.pinchDeltaPercentage) {
  48030. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48031. }
  48032. else {
  48033. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48034. (_this.pinchPrecision *
  48035. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48036. direction);
  48037. }
  48038. previousMultiTouchPanPosition.isPaning = false;
  48039. previousMultiTouchPanPosition.isPinching = true;
  48040. }
  48041. else {
  48042. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48043. if (!previousMultiTouchPanPosition.isPaning) {
  48044. previousMultiTouchPanPosition.isPaning = true;
  48045. previousMultiTouchPanPosition.isPinching = false;
  48046. previousMultiTouchPanPosition.x = ed.x;
  48047. previousMultiTouchPanPosition.y = ed.y;
  48048. return;
  48049. }
  48050. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48051. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48052. }
  48053. }
  48054. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48055. previousMultiTouchPanPosition.x = ed.x;
  48056. previousMultiTouchPanPosition.y = ed.y;
  48057. }
  48058. }
  48059. previousPinchSquaredDistance = pinchSquaredDistance;
  48060. }
  48061. }
  48062. };
  48063. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48064. this._onContextMenu = function (evt) {
  48065. evt.preventDefault();
  48066. };
  48067. if (!this.camera._useCtrlForPanning) {
  48068. element.addEventListener("contextmenu", this._onContextMenu, false);
  48069. }
  48070. this._onLostFocus = function () {
  48071. //this._keys = [];
  48072. pointA = pointB = null;
  48073. previousPinchSquaredDistance = 0;
  48074. previousMultiTouchPanPosition.isPaning = false;
  48075. previousMultiTouchPanPosition.isPinching = false;
  48076. twoFingerActivityCount = 0;
  48077. cacheSoloPointer = null;
  48078. initialDistance = 0;
  48079. };
  48080. this._onMouseMove = function (evt) {
  48081. if (!engine.isPointerLock) {
  48082. return;
  48083. }
  48084. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48085. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48086. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48087. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48088. if (!noPreventDefault) {
  48089. evt.preventDefault();
  48090. }
  48091. };
  48092. this._onGestureStart = function (e) {
  48093. if (window.MSGesture === undefined) {
  48094. return;
  48095. }
  48096. if (!_this._MSGestureHandler) {
  48097. _this._MSGestureHandler = new MSGesture();
  48098. _this._MSGestureHandler.target = element;
  48099. }
  48100. _this._MSGestureHandler.addPointer(e.pointerId);
  48101. };
  48102. this._onGesture = function (e) {
  48103. _this.camera.radius *= e.scale;
  48104. if (e.preventDefault) {
  48105. if (!noPreventDefault) {
  48106. e.stopPropagation();
  48107. e.preventDefault();
  48108. }
  48109. }
  48110. };
  48111. element.addEventListener("mousemove", this._onMouseMove, false);
  48112. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48113. element.addEventListener("MSGestureChange", this._onGesture, false);
  48114. BABYLON.Tools.RegisterTopRootEvents([
  48115. { name: "blur", handler: this._onLostFocus }
  48116. ]);
  48117. };
  48118. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48119. if (this._onLostFocus) {
  48120. BABYLON.Tools.UnregisterTopRootEvents([
  48121. { name: "blur", handler: this._onLostFocus }
  48122. ]);
  48123. }
  48124. if (element && this._observer) {
  48125. this.camera.getScene().onPointerObservable.remove(this._observer);
  48126. this._observer = null;
  48127. if (this._onContextMenu) {
  48128. element.removeEventListener("contextmenu", this._onContextMenu);
  48129. }
  48130. if (this._onMouseMove) {
  48131. element.removeEventListener("mousemove", this._onMouseMove);
  48132. }
  48133. if (this._onGestureStart) {
  48134. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48135. }
  48136. if (this._onGesture) {
  48137. element.removeEventListener("MSGestureChange", this._onGesture);
  48138. }
  48139. this._isPanClick = false;
  48140. this.pinchInwards = true;
  48141. this._onMouseMove = null;
  48142. this._onGestureStart = null;
  48143. this._onGesture = null;
  48144. this._MSGestureHandler = null;
  48145. this._onLostFocus = null;
  48146. this._onContextMenu = null;
  48147. }
  48148. };
  48149. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48150. return "ArcRotateCameraPointersInput";
  48151. };
  48152. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48153. return "pointers";
  48154. };
  48155. __decorate([
  48156. BABYLON.serialize()
  48157. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48158. __decorate([
  48159. BABYLON.serialize()
  48160. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48161. __decorate([
  48162. BABYLON.serialize()
  48163. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48179. return ArcRotateCameraPointersInput;
  48180. }());
  48181. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48182. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48183. })(BABYLON || (BABYLON = {}));
  48184. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48185. var BABYLON;
  48186. (function (BABYLON) {
  48187. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48188. __extends(ArcRotateCameraInputsManager, _super);
  48189. function ArcRotateCameraInputsManager(camera) {
  48190. return _super.call(this, camera) || this;
  48191. }
  48192. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48193. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48194. return this;
  48195. };
  48196. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48197. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48198. return this;
  48199. };
  48200. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48201. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48202. return this;
  48203. };
  48204. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48205. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48206. return this;
  48207. };
  48208. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48209. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48210. return this;
  48211. };
  48212. return ArcRotateCameraInputsManager;
  48213. }(BABYLON.CameraInputsManager));
  48214. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48215. })(BABYLON || (BABYLON = {}));
  48216. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48217. var BABYLON;
  48218. (function (BABYLON) {
  48219. var ArcRotateCamera = /** @class */ (function (_super) {
  48220. __extends(ArcRotateCamera, _super);
  48221. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48222. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48223. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48224. _this.inertialAlphaOffset = 0;
  48225. _this.inertialBetaOffset = 0;
  48226. _this.inertialRadiusOffset = 0;
  48227. _this.lowerAlphaLimit = null;
  48228. _this.upperAlphaLimit = null;
  48229. _this.lowerBetaLimit = 0.01;
  48230. _this.upperBetaLimit = Math.PI;
  48231. _this.lowerRadiusLimit = null;
  48232. _this.upperRadiusLimit = null;
  48233. _this.inertialPanningX = 0;
  48234. _this.inertialPanningY = 0;
  48235. _this.pinchToPanMaxDistance = 20;
  48236. _this.panningDistanceLimit = null;
  48237. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48238. _this.panningInertia = 0.9;
  48239. //-- end properties for backward compatibility for inputs
  48240. _this.zoomOnFactor = 1;
  48241. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48242. _this.allowUpsideDown = true;
  48243. _this._viewMatrix = new BABYLON.Matrix();
  48244. // Panning
  48245. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48246. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48247. _this.checkCollisions = false;
  48248. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48249. _this._previousPosition = BABYLON.Vector3.Zero();
  48250. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48251. _this._newPosition = BABYLON.Vector3.Zero();
  48252. _this._computationVector = BABYLON.Vector3.Zero();
  48253. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48254. if (collidedMesh === void 0) { collidedMesh = null; }
  48255. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48256. newPosition.multiplyInPlace(_this._collider._radius);
  48257. }
  48258. if (!collidedMesh) {
  48259. _this._previousPosition.copyFrom(_this.position);
  48260. }
  48261. else {
  48262. _this.setPosition(newPosition);
  48263. if (_this.onCollide) {
  48264. _this.onCollide(collidedMesh);
  48265. }
  48266. }
  48267. // Recompute because of constraints
  48268. var cosa = Math.cos(_this.alpha);
  48269. var sina = Math.sin(_this.alpha);
  48270. var cosb = Math.cos(_this.beta);
  48271. var sinb = Math.sin(_this.beta);
  48272. if (sinb === 0) {
  48273. sinb = 0.0001;
  48274. }
  48275. var target = _this._getTargetPosition();
  48276. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48277. target.addToRef(_this._computationVector, _this._newPosition);
  48278. _this.position.copyFrom(_this._newPosition);
  48279. var up = _this.upVector;
  48280. if (_this.allowUpsideDown && _this.beta < 0) {
  48281. up = up.clone();
  48282. up = up.negate();
  48283. }
  48284. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48285. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48286. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48287. _this._collisionTriggered = false;
  48288. };
  48289. _this._target = BABYLON.Vector3.Zero();
  48290. if (target) {
  48291. _this.setTarget(target);
  48292. }
  48293. _this.alpha = alpha;
  48294. _this.beta = beta;
  48295. _this.radius = radius;
  48296. _this.getViewMatrix();
  48297. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48298. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48299. return _this;
  48300. }
  48301. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48302. get: function () {
  48303. return this._target;
  48304. },
  48305. set: function (value) {
  48306. this.setTarget(value);
  48307. },
  48308. enumerable: true,
  48309. configurable: true
  48310. });
  48311. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48312. //-- begin properties for backward compatibility for inputs
  48313. get: function () {
  48314. var pointers = this.inputs.attached["pointers"];
  48315. if (pointers)
  48316. return pointers.angularSensibilityX;
  48317. return 0;
  48318. },
  48319. set: function (value) {
  48320. var pointers = this.inputs.attached["pointers"];
  48321. if (pointers) {
  48322. pointers.angularSensibilityX = value;
  48323. }
  48324. },
  48325. enumerable: true,
  48326. configurable: true
  48327. });
  48328. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48329. get: function () {
  48330. var pointers = this.inputs.attached["pointers"];
  48331. if (pointers)
  48332. return pointers.angularSensibilityY;
  48333. return 0;
  48334. },
  48335. set: function (value) {
  48336. var pointers = this.inputs.attached["pointers"];
  48337. if (pointers) {
  48338. pointers.angularSensibilityY = value;
  48339. }
  48340. },
  48341. enumerable: true,
  48342. configurable: true
  48343. });
  48344. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48345. get: function () {
  48346. var pointers = this.inputs.attached["pointers"];
  48347. if (pointers)
  48348. return pointers.pinchPrecision;
  48349. return 0;
  48350. },
  48351. set: function (value) {
  48352. var pointers = this.inputs.attached["pointers"];
  48353. if (pointers) {
  48354. pointers.pinchPrecision = value;
  48355. }
  48356. },
  48357. enumerable: true,
  48358. configurable: true
  48359. });
  48360. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48361. get: function () {
  48362. var pointers = this.inputs.attached["pointers"];
  48363. if (pointers)
  48364. return pointers.pinchDeltaPercentage;
  48365. return 0;
  48366. },
  48367. set: function (value) {
  48368. var pointers = this.inputs.attached["pointers"];
  48369. if (pointers) {
  48370. pointers.pinchDeltaPercentage = value;
  48371. }
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48377. get: function () {
  48378. var pointers = this.inputs.attached["pointers"];
  48379. if (pointers)
  48380. return pointers.panningSensibility;
  48381. return 0;
  48382. },
  48383. set: function (value) {
  48384. var pointers = this.inputs.attached["pointers"];
  48385. if (pointers) {
  48386. pointers.panningSensibility = value;
  48387. }
  48388. },
  48389. enumerable: true,
  48390. configurable: true
  48391. });
  48392. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48393. get: function () {
  48394. var keyboard = this.inputs.attached["keyboard"];
  48395. if (keyboard)
  48396. return keyboard.keysUp;
  48397. return [];
  48398. },
  48399. set: function (value) {
  48400. var keyboard = this.inputs.attached["keyboard"];
  48401. if (keyboard)
  48402. keyboard.keysUp = value;
  48403. },
  48404. enumerable: true,
  48405. configurable: true
  48406. });
  48407. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48408. get: function () {
  48409. var keyboard = this.inputs.attached["keyboard"];
  48410. if (keyboard)
  48411. return keyboard.keysDown;
  48412. return [];
  48413. },
  48414. set: function (value) {
  48415. var keyboard = this.inputs.attached["keyboard"];
  48416. if (keyboard)
  48417. keyboard.keysDown = value;
  48418. },
  48419. enumerable: true,
  48420. configurable: true
  48421. });
  48422. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48423. get: function () {
  48424. var keyboard = this.inputs.attached["keyboard"];
  48425. if (keyboard)
  48426. return keyboard.keysLeft;
  48427. return [];
  48428. },
  48429. set: function (value) {
  48430. var keyboard = this.inputs.attached["keyboard"];
  48431. if (keyboard)
  48432. keyboard.keysLeft = value;
  48433. },
  48434. enumerable: true,
  48435. configurable: true
  48436. });
  48437. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48438. get: function () {
  48439. var keyboard = this.inputs.attached["keyboard"];
  48440. if (keyboard)
  48441. return keyboard.keysRight;
  48442. return [];
  48443. },
  48444. set: function (value) {
  48445. var keyboard = this.inputs.attached["keyboard"];
  48446. if (keyboard)
  48447. keyboard.keysRight = value;
  48448. },
  48449. enumerable: true,
  48450. configurable: true
  48451. });
  48452. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48453. get: function () {
  48454. var mousewheel = this.inputs.attached["mousewheel"];
  48455. if (mousewheel)
  48456. return mousewheel.wheelPrecision;
  48457. return 0;
  48458. },
  48459. set: function (value) {
  48460. var mousewheel = this.inputs.attached["mousewheel"];
  48461. if (mousewheel)
  48462. mousewheel.wheelPrecision = value;
  48463. },
  48464. enumerable: true,
  48465. configurable: true
  48466. });
  48467. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48468. get: function () {
  48469. var mousewheel = this.inputs.attached["mousewheel"];
  48470. if (mousewheel)
  48471. return mousewheel.wheelDeltaPercentage;
  48472. return 0;
  48473. },
  48474. set: function (value) {
  48475. var mousewheel = this.inputs.attached["mousewheel"];
  48476. if (mousewheel)
  48477. mousewheel.wheelDeltaPercentage = value;
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48483. get: function () {
  48484. return this._bouncingBehavior;
  48485. },
  48486. enumerable: true,
  48487. configurable: true
  48488. });
  48489. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48490. get: function () {
  48491. return this._bouncingBehavior != null;
  48492. },
  48493. set: function (value) {
  48494. if (value === this.useBouncingBehavior) {
  48495. return;
  48496. }
  48497. if (value) {
  48498. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48499. this.addBehavior(this._bouncingBehavior);
  48500. }
  48501. else if (this._bouncingBehavior) {
  48502. this.removeBehavior(this._bouncingBehavior);
  48503. this._bouncingBehavior = null;
  48504. }
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48510. get: function () {
  48511. return this._framingBehavior;
  48512. },
  48513. enumerable: true,
  48514. configurable: true
  48515. });
  48516. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48517. get: function () {
  48518. return this._framingBehavior != null;
  48519. },
  48520. set: function (value) {
  48521. if (value === this.useFramingBehavior) {
  48522. return;
  48523. }
  48524. if (value) {
  48525. this._framingBehavior = new BABYLON.FramingBehavior();
  48526. this.addBehavior(this._framingBehavior);
  48527. }
  48528. else if (this._framingBehavior) {
  48529. this.removeBehavior(this._framingBehavior);
  48530. this._framingBehavior = null;
  48531. }
  48532. },
  48533. enumerable: true,
  48534. configurable: true
  48535. });
  48536. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48537. get: function () {
  48538. return this._autoRotationBehavior;
  48539. },
  48540. enumerable: true,
  48541. configurable: true
  48542. });
  48543. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48544. get: function () {
  48545. return this._autoRotationBehavior != null;
  48546. },
  48547. set: function (value) {
  48548. if (value === this.useAutoRotationBehavior) {
  48549. return;
  48550. }
  48551. if (value) {
  48552. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48553. this.addBehavior(this._autoRotationBehavior);
  48554. }
  48555. else if (this._autoRotationBehavior) {
  48556. this.removeBehavior(this._autoRotationBehavior);
  48557. this._autoRotationBehavior = null;
  48558. }
  48559. },
  48560. enumerable: true,
  48561. configurable: true
  48562. });
  48563. // Cache
  48564. ArcRotateCamera.prototype._initCache = function () {
  48565. _super.prototype._initCache.call(this);
  48566. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48567. this._cache.alpha = undefined;
  48568. this._cache.beta = undefined;
  48569. this._cache.radius = undefined;
  48570. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48571. };
  48572. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48573. if (!ignoreParentClass) {
  48574. _super.prototype._updateCache.call(this);
  48575. }
  48576. this._cache._target.copyFrom(this._getTargetPosition());
  48577. this._cache.alpha = this.alpha;
  48578. this._cache.beta = this.beta;
  48579. this._cache.radius = this.radius;
  48580. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48581. };
  48582. ArcRotateCamera.prototype._getTargetPosition = function () {
  48583. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48584. var pos = this._targetHost.getAbsolutePosition();
  48585. if (this._targetBoundingCenter) {
  48586. pos.addToRef(this._targetBoundingCenter, this._target);
  48587. }
  48588. else {
  48589. this._target.copyFrom(pos);
  48590. }
  48591. }
  48592. var lockedTargetPosition = this._getLockedTargetPosition();
  48593. if (lockedTargetPosition) {
  48594. return lockedTargetPosition;
  48595. }
  48596. return this._target;
  48597. };
  48598. ArcRotateCamera.prototype.storeState = function () {
  48599. this._storedAlpha = this.alpha;
  48600. this._storedBeta = this.beta;
  48601. this._storedRadius = this.radius;
  48602. this._storedTarget = this._getTargetPosition().clone();
  48603. return _super.prototype.storeState.call(this);
  48604. };
  48605. /**
  48606. * Restored camera state. You must call storeState() first
  48607. */
  48608. ArcRotateCamera.prototype._restoreStateValues = function () {
  48609. if (!_super.prototype._restoreStateValues.call(this)) {
  48610. return false;
  48611. }
  48612. this.alpha = this._storedAlpha;
  48613. this.beta = this._storedBeta;
  48614. this.radius = this._storedRadius;
  48615. this.setTarget(this._storedTarget.clone());
  48616. this.inertialAlphaOffset = 0;
  48617. this.inertialBetaOffset = 0;
  48618. this.inertialRadiusOffset = 0;
  48619. this.inertialPanningX = 0;
  48620. this.inertialPanningY = 0;
  48621. return true;
  48622. };
  48623. // Synchronized
  48624. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48625. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48626. return false;
  48627. return this._cache._target.equals(this._getTargetPosition())
  48628. && this._cache.alpha === this.alpha
  48629. && this._cache.beta === this.beta
  48630. && this._cache.radius === this.radius
  48631. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48632. };
  48633. // Methods
  48634. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48635. var _this = this;
  48636. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48637. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48638. this._useCtrlForPanning = useCtrlForPanning;
  48639. this._panningMouseButton = panningMouseButton;
  48640. this.inputs.attachElement(element, noPreventDefault);
  48641. this._reset = function () {
  48642. _this.inertialAlphaOffset = 0;
  48643. _this.inertialBetaOffset = 0;
  48644. _this.inertialRadiusOffset = 0;
  48645. _this.inertialPanningX = 0;
  48646. _this.inertialPanningY = 0;
  48647. };
  48648. };
  48649. ArcRotateCamera.prototype.detachControl = function (element) {
  48650. this.inputs.detachElement(element);
  48651. if (this._reset) {
  48652. this._reset();
  48653. }
  48654. };
  48655. ArcRotateCamera.prototype._checkInputs = function () {
  48656. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48657. if (this._collisionTriggered) {
  48658. return;
  48659. }
  48660. this.inputs.checkInputs();
  48661. // Inertia
  48662. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48663. var inertialAlphaOffset = this.inertialAlphaOffset;
  48664. if (this.beta <= 0)
  48665. inertialAlphaOffset *= -1;
  48666. if (this.getScene().useRightHandedSystem)
  48667. inertialAlphaOffset *= -1;
  48668. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48669. inertialAlphaOffset *= -1;
  48670. this.alpha += inertialAlphaOffset;
  48671. this.beta += this.inertialBetaOffset;
  48672. this.radius -= this.inertialRadiusOffset;
  48673. this.inertialAlphaOffset *= this.inertia;
  48674. this.inertialBetaOffset *= this.inertia;
  48675. this.inertialRadiusOffset *= this.inertia;
  48676. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48677. this.inertialAlphaOffset = 0;
  48678. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48679. this.inertialBetaOffset = 0;
  48680. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48681. this.inertialRadiusOffset = 0;
  48682. }
  48683. // Panning inertia
  48684. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48685. if (!this._localDirection) {
  48686. this._localDirection = BABYLON.Vector3.Zero();
  48687. this._transformedDirection = BABYLON.Vector3.Zero();
  48688. }
  48689. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48690. this._localDirection.multiplyInPlace(this.panningAxis);
  48691. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48692. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48693. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48694. if (!this.panningAxis.y) {
  48695. this._transformedDirection.y = 0;
  48696. }
  48697. if (!this._targetHost) {
  48698. if (this.panningDistanceLimit) {
  48699. this._transformedDirection.addInPlace(this._target);
  48700. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48701. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48702. this._target.copyFrom(this._transformedDirection);
  48703. }
  48704. }
  48705. else {
  48706. this._target.addInPlace(this._transformedDirection);
  48707. }
  48708. }
  48709. this.inertialPanningX *= this.panningInertia;
  48710. this.inertialPanningY *= this.panningInertia;
  48711. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48712. this.inertialPanningX = 0;
  48713. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48714. this.inertialPanningY = 0;
  48715. }
  48716. // Limits
  48717. this._checkLimits();
  48718. _super.prototype._checkInputs.call(this);
  48719. };
  48720. ArcRotateCamera.prototype._checkLimits = function () {
  48721. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48722. if (this.allowUpsideDown && this.beta > Math.PI) {
  48723. this.beta = this.beta - (2 * Math.PI);
  48724. }
  48725. }
  48726. else {
  48727. if (this.beta < this.lowerBetaLimit) {
  48728. this.beta = this.lowerBetaLimit;
  48729. }
  48730. }
  48731. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48732. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48733. this.beta = this.beta + (2 * Math.PI);
  48734. }
  48735. }
  48736. else {
  48737. if (this.beta > this.upperBetaLimit) {
  48738. this.beta = this.upperBetaLimit;
  48739. }
  48740. }
  48741. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48742. this.alpha = this.lowerAlphaLimit;
  48743. }
  48744. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48745. this.alpha = this.upperAlphaLimit;
  48746. }
  48747. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48748. this.radius = this.lowerRadiusLimit;
  48749. }
  48750. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48751. this.radius = this.upperRadiusLimit;
  48752. }
  48753. };
  48754. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48755. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48756. this.radius = this._computationVector.length();
  48757. if (this.radius === 0) {
  48758. this.radius = 0.0001; // Just to avoid division by zero
  48759. }
  48760. // Alpha
  48761. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48762. if (this._computationVector.z < 0) {
  48763. this.alpha = 2 * Math.PI - this.alpha;
  48764. }
  48765. // Beta
  48766. this.beta = Math.acos(this._computationVector.y / this.radius);
  48767. this._checkLimits();
  48768. };
  48769. ArcRotateCamera.prototype.setPosition = function (position) {
  48770. if (this.position.equals(position)) {
  48771. return;
  48772. }
  48773. this.position.copyFrom(position);
  48774. this.rebuildAnglesAndRadius();
  48775. };
  48776. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48777. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48778. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48779. if (target.getBoundingInfo) {
  48780. if (toBoundingCenter) {
  48781. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48782. }
  48783. else {
  48784. this._targetBoundingCenter = null;
  48785. }
  48786. this._targetHost = target;
  48787. this._target = this._getTargetPosition();
  48788. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48789. }
  48790. else {
  48791. var newTarget = target;
  48792. var currentTarget = this._getTargetPosition();
  48793. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48794. return;
  48795. }
  48796. this._targetHost = null;
  48797. this._target = newTarget;
  48798. this._targetBoundingCenter = null;
  48799. this.onMeshTargetChangedObservable.notifyObservers(null);
  48800. }
  48801. this.rebuildAnglesAndRadius();
  48802. };
  48803. ArcRotateCamera.prototype._getViewMatrix = function () {
  48804. // Compute
  48805. var cosa = Math.cos(this.alpha);
  48806. var sina = Math.sin(this.alpha);
  48807. var cosb = Math.cos(this.beta);
  48808. var sinb = Math.sin(this.beta);
  48809. if (sinb === 0) {
  48810. sinb = 0.0001;
  48811. }
  48812. var target = this._getTargetPosition();
  48813. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48814. target.addToRef(this._computationVector, this._newPosition);
  48815. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48816. if (!this._collider) {
  48817. this._collider = new BABYLON.Collider();
  48818. }
  48819. this._collider._radius = this.collisionRadius;
  48820. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48821. this._collisionTriggered = true;
  48822. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48823. }
  48824. else {
  48825. this.position.copyFrom(this._newPosition);
  48826. var up = this.upVector;
  48827. if (this.allowUpsideDown && sinb < 0) {
  48828. up = up.clone();
  48829. up = up.negate();
  48830. }
  48831. this._computeViewMatrix(this.position, target, up);
  48832. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48833. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48834. }
  48835. this._currentTarget = target;
  48836. return this._viewMatrix;
  48837. };
  48838. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48839. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48840. meshes = meshes || this.getScene().meshes;
  48841. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48842. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48843. this.radius = distance * this.zoomOnFactor;
  48844. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48845. };
  48846. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48847. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48848. var meshesOrMinMaxVector;
  48849. var distance;
  48850. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48851. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48852. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48853. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48854. }
  48855. else { //minMaxVector and distance
  48856. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48857. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48858. distance = minMaxVectorAndDistance.distance;
  48859. }
  48860. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48861. if (!doNotUpdateMaxZ) {
  48862. this.maxZ = distance * 2;
  48863. }
  48864. };
  48865. /**
  48866. * @override
  48867. * Override Camera.createRigCamera
  48868. */
  48869. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48870. var alphaShift = 0;
  48871. switch (this.cameraRigMode) {
  48872. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48873. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48874. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48875. case BABYLON.Camera.RIG_MODE_VR:
  48876. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48877. break;
  48878. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48879. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48880. break;
  48881. }
  48882. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48883. rigCam._cameraRigParams = {};
  48884. return rigCam;
  48885. };
  48886. /**
  48887. * @override
  48888. * Override Camera._updateRigCameras
  48889. */
  48890. ArcRotateCamera.prototype._updateRigCameras = function () {
  48891. var camLeft = this._rigCameras[0];
  48892. var camRight = this._rigCameras[1];
  48893. camLeft.beta = camRight.beta = this.beta;
  48894. camLeft.radius = camRight.radius = this.radius;
  48895. switch (this.cameraRigMode) {
  48896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48897. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48899. case BABYLON.Camera.RIG_MODE_VR:
  48900. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48901. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48902. break;
  48903. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48904. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48905. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48906. break;
  48907. }
  48908. _super.prototype._updateRigCameras.call(this);
  48909. };
  48910. ArcRotateCamera.prototype.dispose = function () {
  48911. this.inputs.clear();
  48912. _super.prototype.dispose.call(this);
  48913. };
  48914. ArcRotateCamera.prototype.getClassName = function () {
  48915. return "ArcRotateCamera";
  48916. };
  48917. __decorate([
  48918. BABYLON.serialize()
  48919. ], ArcRotateCamera.prototype, "alpha", void 0);
  48920. __decorate([
  48921. BABYLON.serialize()
  48922. ], ArcRotateCamera.prototype, "beta", void 0);
  48923. __decorate([
  48924. BABYLON.serialize()
  48925. ], ArcRotateCamera.prototype, "radius", void 0);
  48926. __decorate([
  48927. BABYLON.serializeAsVector3("target")
  48928. ], ArcRotateCamera.prototype, "_target", void 0);
  48929. __decorate([
  48930. BABYLON.serialize()
  48931. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48932. __decorate([
  48933. BABYLON.serialize()
  48934. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48935. __decorate([
  48936. BABYLON.serialize()
  48937. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48938. __decorate([
  48939. BABYLON.serialize()
  48940. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48941. __decorate([
  48942. BABYLON.serialize()
  48943. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48944. __decorate([
  48945. BABYLON.serialize()
  48946. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48947. __decorate([
  48948. BABYLON.serialize()
  48949. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48950. __decorate([
  48951. BABYLON.serialize()
  48952. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48953. __decorate([
  48954. BABYLON.serialize()
  48955. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48956. __decorate([
  48957. BABYLON.serialize()
  48958. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48959. __decorate([
  48960. BABYLON.serialize()
  48961. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48962. __decorate([
  48963. BABYLON.serialize()
  48964. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48965. __decorate([
  48966. BABYLON.serialize()
  48967. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48968. __decorate([
  48969. BABYLON.serializeAsVector3()
  48970. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48971. __decorate([
  48972. BABYLON.serialize()
  48973. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48974. __decorate([
  48975. BABYLON.serialize()
  48976. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48977. __decorate([
  48978. BABYLON.serialize()
  48979. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48980. return ArcRotateCamera;
  48981. }(BABYLON.TargetCamera));
  48982. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48983. })(BABYLON || (BABYLON = {}));
  48984. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48985. var BABYLON;
  48986. (function (BABYLON) {
  48987. /**
  48988. * The HemisphericLight simulates the ambient environment light,
  48989. * so the passed direction is the light reflection direction, not the incoming direction.
  48990. */
  48991. var HemisphericLight = /** @class */ (function (_super) {
  48992. __extends(HemisphericLight, _super);
  48993. /**
  48994. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48995. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48996. * The HemisphericLight can't cast shadows.
  48997. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48998. * @param name The friendly name of the light
  48999. * @param direction The direction of the light reflection
  49000. * @param scene The scene the light belongs to
  49001. */
  49002. function HemisphericLight(name, direction, scene) {
  49003. var _this = _super.call(this, name, scene) || this;
  49004. /**
  49005. * The groundColor is the light in the opposite direction to the one specified during creation.
  49006. * 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.
  49007. */
  49008. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49009. _this.direction = direction || BABYLON.Vector3.Up();
  49010. return _this;
  49011. }
  49012. HemisphericLight.prototype._buildUniformLayout = function () {
  49013. this._uniformBuffer.addUniform("vLightData", 4);
  49014. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49015. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49016. this._uniformBuffer.addUniform("vLightGround", 3);
  49017. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49018. this._uniformBuffer.addUniform("depthValues", 2);
  49019. this._uniformBuffer.create();
  49020. };
  49021. /**
  49022. * Returns the string "HemisphericLight".
  49023. * @return The class name
  49024. */
  49025. HemisphericLight.prototype.getClassName = function () {
  49026. return "HemisphericLight";
  49027. };
  49028. /**
  49029. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49030. * Returns the updated direction.
  49031. * @param target The target the direction should point to
  49032. * @return The computed direction
  49033. */
  49034. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49035. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49036. return this.direction;
  49037. };
  49038. /**
  49039. * Returns the shadow generator associated to the light.
  49040. * @returns Always null for hemispheric lights because it does not support shadows.
  49041. */
  49042. HemisphericLight.prototype.getShadowGenerator = function () {
  49043. return null;
  49044. };
  49045. /**
  49046. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49047. * @param effect The effect to update
  49048. * @param lightIndex The index of the light in the effect to update
  49049. * @returns The hemispheric light
  49050. */
  49051. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49052. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49053. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49054. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49055. return this;
  49056. };
  49057. /**
  49058. * @hidden internal use only.
  49059. */
  49060. HemisphericLight.prototype._getWorldMatrix = function () {
  49061. if (!this._worldMatrix) {
  49062. this._worldMatrix = BABYLON.Matrix.Identity();
  49063. }
  49064. return this._worldMatrix;
  49065. };
  49066. /**
  49067. * Returns the integer 3.
  49068. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49069. */
  49070. HemisphericLight.prototype.getTypeID = function () {
  49071. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49072. };
  49073. __decorate([
  49074. BABYLON.serializeAsColor3()
  49075. ], HemisphericLight.prototype, "groundColor", void 0);
  49076. __decorate([
  49077. BABYLON.serializeAsVector3()
  49078. ], HemisphericLight.prototype, "direction", void 0);
  49079. return HemisphericLight;
  49080. }(BABYLON.Light));
  49081. BABYLON.HemisphericLight = HemisphericLight;
  49082. })(BABYLON || (BABYLON = {}));
  49083. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49084. var BABYLON;
  49085. (function (BABYLON) {
  49086. /**
  49087. * Base implementation IShadowLight
  49088. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49089. */
  49090. var ShadowLight = /** @class */ (function (_super) {
  49091. __extends(ShadowLight, _super);
  49092. function ShadowLight() {
  49093. var _this = _super !== null && _super.apply(this, arguments) || this;
  49094. _this._needProjectionMatrixCompute = true;
  49095. return _this;
  49096. }
  49097. ShadowLight.prototype._setPosition = function (value) {
  49098. this._position = value;
  49099. };
  49100. Object.defineProperty(ShadowLight.prototype, "position", {
  49101. /**
  49102. * Sets the position the shadow will be casted from. Also use as the light position for both
  49103. * point and spot lights.
  49104. */
  49105. get: function () {
  49106. return this._position;
  49107. },
  49108. /**
  49109. * Sets the position the shadow will be casted from. Also use as the light position for both
  49110. * point and spot lights.
  49111. */
  49112. set: function (value) {
  49113. this._setPosition(value);
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. ShadowLight.prototype._setDirection = function (value) {
  49119. this._direction = value;
  49120. };
  49121. Object.defineProperty(ShadowLight.prototype, "direction", {
  49122. /**
  49123. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49124. * Also use as the light direction on spot and directional lights.
  49125. */
  49126. get: function () {
  49127. return this._direction;
  49128. },
  49129. /**
  49130. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49131. * Also use as the light direction on spot and directional lights.
  49132. */
  49133. set: function (value) {
  49134. this._setDirection(value);
  49135. },
  49136. enumerable: true,
  49137. configurable: true
  49138. });
  49139. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49140. /**
  49141. * Gets the shadow projection clipping minimum z value.
  49142. */
  49143. get: function () {
  49144. return this._shadowMinZ;
  49145. },
  49146. /**
  49147. * Sets the shadow projection clipping minimum z value.
  49148. */
  49149. set: function (value) {
  49150. this._shadowMinZ = value;
  49151. this.forceProjectionMatrixCompute();
  49152. },
  49153. enumerable: true,
  49154. configurable: true
  49155. });
  49156. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49157. /**
  49158. * Sets the shadow projection clipping maximum z value.
  49159. */
  49160. get: function () {
  49161. return this._shadowMaxZ;
  49162. },
  49163. /**
  49164. * Gets the shadow projection clipping maximum z value.
  49165. */
  49166. set: function (value) {
  49167. this._shadowMaxZ = value;
  49168. this.forceProjectionMatrixCompute();
  49169. },
  49170. enumerable: true,
  49171. configurable: true
  49172. });
  49173. /**
  49174. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49175. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49176. */
  49177. ShadowLight.prototype.computeTransformedInformation = function () {
  49178. if (this.parent && this.parent.getWorldMatrix) {
  49179. if (!this.transformedPosition) {
  49180. this.transformedPosition = BABYLON.Vector3.Zero();
  49181. }
  49182. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49183. // In case the direction is present.
  49184. if (this.direction) {
  49185. if (!this.transformedDirection) {
  49186. this.transformedDirection = BABYLON.Vector3.Zero();
  49187. }
  49188. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49189. }
  49190. return true;
  49191. }
  49192. return false;
  49193. };
  49194. /**
  49195. * Return the depth scale used for the shadow map.
  49196. * @returns the depth scale.
  49197. */
  49198. ShadowLight.prototype.getDepthScale = function () {
  49199. return 50.0;
  49200. };
  49201. /**
  49202. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49203. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49204. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49205. */
  49206. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49207. return this.transformedDirection ? this.transformedDirection : this.direction;
  49208. };
  49209. /**
  49210. * Returns the ShadowLight absolute position in the World.
  49211. * @returns the position vector in world space
  49212. */
  49213. ShadowLight.prototype.getAbsolutePosition = function () {
  49214. return this.transformedPosition ? this.transformedPosition : this.position;
  49215. };
  49216. /**
  49217. * Sets the ShadowLight direction toward the passed target.
  49218. * @param target The point tot target in local space
  49219. * @returns the updated ShadowLight direction
  49220. */
  49221. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49222. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49223. return this.direction;
  49224. };
  49225. /**
  49226. * Returns the light rotation in euler definition.
  49227. * @returns the x y z rotation in local space.
  49228. */
  49229. ShadowLight.prototype.getRotation = function () {
  49230. this.direction.normalize();
  49231. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49232. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49233. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49234. };
  49235. /**
  49236. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49237. * @returns true if a cube texture needs to be use
  49238. */
  49239. ShadowLight.prototype.needCube = function () {
  49240. return false;
  49241. };
  49242. /**
  49243. * Detects if the projection matrix requires to be recomputed this frame.
  49244. * @returns true if it requires to be recomputed otherwise, false.
  49245. */
  49246. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49247. return this._needProjectionMatrixCompute;
  49248. };
  49249. /**
  49250. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49251. */
  49252. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49253. this._needProjectionMatrixCompute = true;
  49254. };
  49255. /**
  49256. * Get the world matrix of the sahdow lights.
  49257. * @hidden Internal Use Only
  49258. */
  49259. ShadowLight.prototype._getWorldMatrix = function () {
  49260. if (!this._worldMatrix) {
  49261. this._worldMatrix = BABYLON.Matrix.Identity();
  49262. }
  49263. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49264. return this._worldMatrix;
  49265. };
  49266. /**
  49267. * Gets the minZ used for shadow according to both the scene and the light.
  49268. * @param activeCamera The camera we are returning the min for
  49269. * @returns the depth min z
  49270. */
  49271. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49272. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49273. };
  49274. /**
  49275. * Gets the maxZ used for shadow according to both the scene and the light.
  49276. * @param activeCamera The camera we are returning the max for
  49277. * @returns the depth max z
  49278. */
  49279. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49280. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49281. };
  49282. /**
  49283. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49284. * @param matrix The materix to updated with the projection information
  49285. * @param viewMatrix The transform matrix of the light
  49286. * @param renderList The list of mesh to render in the map
  49287. * @returns The current light
  49288. */
  49289. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49290. if (this.customProjectionMatrixBuilder) {
  49291. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49292. }
  49293. else {
  49294. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49295. }
  49296. return this;
  49297. };
  49298. __decorate([
  49299. BABYLON.serializeAsVector3()
  49300. ], ShadowLight.prototype, "position", null);
  49301. __decorate([
  49302. BABYLON.serializeAsVector3()
  49303. ], ShadowLight.prototype, "direction", null);
  49304. __decorate([
  49305. BABYLON.serialize()
  49306. ], ShadowLight.prototype, "shadowMinZ", null);
  49307. __decorate([
  49308. BABYLON.serialize()
  49309. ], ShadowLight.prototype, "shadowMaxZ", null);
  49310. return ShadowLight;
  49311. }(BABYLON.Light));
  49312. BABYLON.ShadowLight = ShadowLight;
  49313. })(BABYLON || (BABYLON = {}));
  49314. //# sourceMappingURL=babylon.shadowLight.js.map
  49315. var BABYLON;
  49316. (function (BABYLON) {
  49317. /**
  49318. * A point light is a light defined by an unique point in world space.
  49319. * The light is emitted in every direction from this point.
  49320. * A good example of a point light is a standard light bulb.
  49321. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49322. */
  49323. var PointLight = /** @class */ (function (_super) {
  49324. __extends(PointLight, _super);
  49325. /**
  49326. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49327. * A PointLight emits the light in every direction.
  49328. * It can cast shadows.
  49329. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49330. * ```javascript
  49331. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49332. * ```
  49333. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49334. * @param name The light friendly name
  49335. * @param position The position of the point light in the scene
  49336. * @param scene The scene the lights belongs to
  49337. */
  49338. function PointLight(name, position, scene) {
  49339. var _this = _super.call(this, name, scene) || this;
  49340. _this._shadowAngle = Math.PI / 2;
  49341. _this.position = position;
  49342. return _this;
  49343. }
  49344. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49345. /**
  49346. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49347. * This specifies what angle the shadow will use to be created.
  49348. *
  49349. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49350. */
  49351. get: function () {
  49352. return this._shadowAngle;
  49353. },
  49354. /**
  49355. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49356. * This specifies what angle the shadow will use to be created.
  49357. *
  49358. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49359. */
  49360. set: function (value) {
  49361. this._shadowAngle = value;
  49362. this.forceProjectionMatrixCompute();
  49363. },
  49364. enumerable: true,
  49365. configurable: true
  49366. });
  49367. Object.defineProperty(PointLight.prototype, "direction", {
  49368. /**
  49369. * Gets the direction if it has been set.
  49370. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49371. */
  49372. get: function () {
  49373. return this._direction;
  49374. },
  49375. /**
  49376. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49377. */
  49378. set: function (value) {
  49379. var previousNeedCube = this.needCube();
  49380. this._direction = value;
  49381. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49382. this._shadowGenerator.recreateShadowMap();
  49383. }
  49384. },
  49385. enumerable: true,
  49386. configurable: true
  49387. });
  49388. /**
  49389. * Returns the string "PointLight"
  49390. * @returns the class name
  49391. */
  49392. PointLight.prototype.getClassName = function () {
  49393. return "PointLight";
  49394. };
  49395. /**
  49396. * Returns the integer 0.
  49397. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49398. */
  49399. PointLight.prototype.getTypeID = function () {
  49400. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49401. };
  49402. /**
  49403. * Specifies wether or not the shadowmap should be a cube texture.
  49404. * @returns true if the shadowmap needs to be a cube texture.
  49405. */
  49406. PointLight.prototype.needCube = function () {
  49407. return !this.direction;
  49408. };
  49409. /**
  49410. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49411. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49412. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49413. */
  49414. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49415. if (this.direction) {
  49416. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49417. }
  49418. else {
  49419. switch (faceIndex) {
  49420. case 0:
  49421. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49422. case 1:
  49423. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49424. case 2:
  49425. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49426. case 3:
  49427. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49428. case 4:
  49429. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49430. case 5:
  49431. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49432. }
  49433. }
  49434. return BABYLON.Vector3.Zero();
  49435. };
  49436. /**
  49437. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49438. * - fov = PI / 2
  49439. * - aspect ratio : 1.0
  49440. * - z-near and far equal to the active camera minZ and maxZ.
  49441. * Returns the PointLight.
  49442. */
  49443. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49444. var activeCamera = this.getScene().activeCamera;
  49445. if (!activeCamera) {
  49446. return;
  49447. }
  49448. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49449. };
  49450. PointLight.prototype._buildUniformLayout = function () {
  49451. this._uniformBuffer.addUniform("vLightData", 4);
  49452. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49453. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49454. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49455. this._uniformBuffer.addUniform("depthValues", 2);
  49456. this._uniformBuffer.create();
  49457. };
  49458. /**
  49459. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49460. * @param effect The effect to update
  49461. * @param lightIndex The index of the light in the effect to update
  49462. * @returns The point light
  49463. */
  49464. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49465. if (this.computeTransformedInformation()) {
  49466. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49467. return this;
  49468. }
  49469. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49470. return this;
  49471. };
  49472. __decorate([
  49473. BABYLON.serialize()
  49474. ], PointLight.prototype, "shadowAngle", null);
  49475. return PointLight;
  49476. }(BABYLON.ShadowLight));
  49477. BABYLON.PointLight = PointLight;
  49478. })(BABYLON || (BABYLON = {}));
  49479. //# sourceMappingURL=babylon.pointLight.js.map
  49480. var BABYLON;
  49481. (function (BABYLON) {
  49482. /**
  49483. * A directional light is defined by a direction (what a surprise!).
  49484. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49485. * 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.
  49486. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49487. */
  49488. var DirectionalLight = /** @class */ (function (_super) {
  49489. __extends(DirectionalLight, _super);
  49490. /**
  49491. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49492. * The directional light is emitted from everywhere in the given direction.
  49493. * It can cast shawdows.
  49494. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49495. * @param name The friendly name of the light
  49496. * @param direction The direction of the light
  49497. * @param scene The scene the light belongs to
  49498. */
  49499. function DirectionalLight(name, direction, scene) {
  49500. var _this = _super.call(this, name, scene) || this;
  49501. _this._shadowFrustumSize = 0;
  49502. _this._shadowOrthoScale = 0.1;
  49503. /**
  49504. * Automatically compute the projection matrix to best fit (including all the casters)
  49505. * on each frame.
  49506. */
  49507. _this.autoUpdateExtends = true;
  49508. // Cache
  49509. _this._orthoLeft = Number.MAX_VALUE;
  49510. _this._orthoRight = Number.MIN_VALUE;
  49511. _this._orthoTop = Number.MIN_VALUE;
  49512. _this._orthoBottom = Number.MAX_VALUE;
  49513. _this.position = direction.scale(-1.0);
  49514. _this.direction = direction;
  49515. return _this;
  49516. }
  49517. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49518. /**
  49519. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49520. */
  49521. get: function () {
  49522. return this._shadowFrustumSize;
  49523. },
  49524. /**
  49525. * Specifies a fix frustum size for the shadow generation.
  49526. */
  49527. set: function (value) {
  49528. this._shadowFrustumSize = value;
  49529. this.forceProjectionMatrixCompute();
  49530. },
  49531. enumerable: true,
  49532. configurable: true
  49533. });
  49534. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49535. /**
  49536. * Gets the shadow projection scale against the optimal computed one.
  49537. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49538. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49539. */
  49540. get: function () {
  49541. return this._shadowOrthoScale;
  49542. },
  49543. /**
  49544. * Sets the shadow projection scale against the optimal computed one.
  49545. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49546. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49547. */
  49548. set: function (value) {
  49549. this._shadowOrthoScale = value;
  49550. this.forceProjectionMatrixCompute();
  49551. },
  49552. enumerable: true,
  49553. configurable: true
  49554. });
  49555. /**
  49556. * Returns the string "DirectionalLight".
  49557. * @return The class name
  49558. */
  49559. DirectionalLight.prototype.getClassName = function () {
  49560. return "DirectionalLight";
  49561. };
  49562. /**
  49563. * Returns the integer 1.
  49564. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49565. */
  49566. DirectionalLight.prototype.getTypeID = function () {
  49567. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49568. };
  49569. /**
  49570. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49571. * Returns the DirectionalLight Shadow projection matrix.
  49572. */
  49573. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49574. if (this.shadowFrustumSize > 0) {
  49575. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49576. }
  49577. else {
  49578. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49579. }
  49580. };
  49581. /**
  49582. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49583. * Returns the DirectionalLight Shadow projection matrix.
  49584. */
  49585. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49586. var activeCamera = this.getScene().activeCamera;
  49587. if (!activeCamera) {
  49588. return;
  49589. }
  49590. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49591. };
  49592. /**
  49593. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49594. * Returns the DirectionalLight Shadow projection matrix.
  49595. */
  49596. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49597. var activeCamera = this.getScene().activeCamera;
  49598. if (!activeCamera) {
  49599. return;
  49600. }
  49601. // Check extends
  49602. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49603. var tempVector3 = BABYLON.Vector3.Zero();
  49604. this._orthoLeft = Number.MAX_VALUE;
  49605. this._orthoRight = Number.MIN_VALUE;
  49606. this._orthoTop = Number.MIN_VALUE;
  49607. this._orthoBottom = Number.MAX_VALUE;
  49608. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49609. var mesh = renderList[meshIndex];
  49610. if (!mesh) {
  49611. continue;
  49612. }
  49613. var boundingInfo = mesh.getBoundingInfo();
  49614. var boundingBox = boundingInfo.boundingBox;
  49615. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49616. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49617. if (tempVector3.x < this._orthoLeft)
  49618. this._orthoLeft = tempVector3.x;
  49619. if (tempVector3.y < this._orthoBottom)
  49620. this._orthoBottom = tempVector3.y;
  49621. if (tempVector3.x > this._orthoRight)
  49622. this._orthoRight = tempVector3.x;
  49623. if (tempVector3.y > this._orthoTop)
  49624. this._orthoTop = tempVector3.y;
  49625. }
  49626. }
  49627. }
  49628. var xOffset = this._orthoRight - this._orthoLeft;
  49629. var yOffset = this._orthoTop - this._orthoBottom;
  49630. 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);
  49631. };
  49632. DirectionalLight.prototype._buildUniformLayout = function () {
  49633. this._uniformBuffer.addUniform("vLightData", 4);
  49634. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49635. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49636. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49637. this._uniformBuffer.addUniform("depthValues", 2);
  49638. this._uniformBuffer.create();
  49639. };
  49640. /**
  49641. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49642. * @param effect The effect to update
  49643. * @param lightIndex The index of the light in the effect to update
  49644. * @returns The directional light
  49645. */
  49646. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49647. if (this.computeTransformedInformation()) {
  49648. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49649. return this;
  49650. }
  49651. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49652. return this;
  49653. };
  49654. /**
  49655. * Gets the minZ used for shadow according to both the scene and the light.
  49656. *
  49657. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49658. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49659. * @param activeCamera The camera we are returning the min for
  49660. * @returns the depth min z
  49661. */
  49662. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49663. return 1;
  49664. };
  49665. /**
  49666. * Gets the maxZ used for shadow according to both the scene and the light.
  49667. *
  49668. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49669. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49670. * @param activeCamera The camera we are returning the max for
  49671. * @returns the depth max z
  49672. */
  49673. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49674. return 1;
  49675. };
  49676. __decorate([
  49677. BABYLON.serialize()
  49678. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49679. __decorate([
  49680. BABYLON.serialize()
  49681. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49682. __decorate([
  49683. BABYLON.serialize()
  49684. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49685. return DirectionalLight;
  49686. }(BABYLON.ShadowLight));
  49687. BABYLON.DirectionalLight = DirectionalLight;
  49688. })(BABYLON || (BABYLON = {}));
  49689. //# sourceMappingURL=babylon.directionalLight.js.map
  49690. var BABYLON;
  49691. (function (BABYLON) {
  49692. /**
  49693. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49694. * These values define a cone of light starting from the position, emitting toward the direction.
  49695. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49696. * and the exponent defines the speed of the decay of the light with distance (reach).
  49697. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49698. */
  49699. var SpotLight = /** @class */ (function (_super) {
  49700. __extends(SpotLight, _super);
  49701. /**
  49702. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49703. * It can cast shadows.
  49704. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49705. * @param name The light friendly name
  49706. * @param position The position of the spot light in the scene
  49707. * @param direction The direction of the light in the scene
  49708. * @param angle The cone angle of the light in Radians
  49709. * @param exponent The light decay speed with the distance from the emission spot
  49710. * @param scene The scene the lights belongs to
  49711. */
  49712. function SpotLight(name, position, direction, angle, exponent, scene) {
  49713. var _this = _super.call(this, name, scene) || this;
  49714. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49715. _this._projectionTextureLightNear = 1e-6;
  49716. _this._projectionTextureLightFar = 1000.0;
  49717. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49718. _this._projectionTextureViewLightDirty = true;
  49719. _this._projectionTextureProjectionLightDirty = true;
  49720. _this._projectionTextureDirty = true;
  49721. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49722. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49723. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49724. _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);
  49725. _this.position = position;
  49726. _this.direction = direction;
  49727. _this.angle = angle;
  49728. _this.exponent = exponent;
  49729. return _this;
  49730. }
  49731. Object.defineProperty(SpotLight.prototype, "angle", {
  49732. /**
  49733. * Gets the cone angle of the spot light in Radians.
  49734. */
  49735. get: function () {
  49736. return this._angle;
  49737. },
  49738. /**
  49739. * Sets the cone angle of the spot light in Radians.
  49740. */
  49741. set: function (value) {
  49742. this._angle = value;
  49743. this._projectionTextureProjectionLightDirty = true;
  49744. this.forceProjectionMatrixCompute();
  49745. },
  49746. enumerable: true,
  49747. configurable: true
  49748. });
  49749. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49750. /**
  49751. * Allows scaling the angle of the light for shadow generation only.
  49752. */
  49753. get: function () {
  49754. return this._shadowAngleScale;
  49755. },
  49756. /**
  49757. * Allows scaling the angle of the light for shadow generation only.
  49758. */
  49759. set: function (value) {
  49760. this._shadowAngleScale = value;
  49761. this.forceProjectionMatrixCompute();
  49762. },
  49763. enumerable: true,
  49764. configurable: true
  49765. });
  49766. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49767. /**
  49768. * Allows reading the projecton texture
  49769. */
  49770. get: function () {
  49771. return this._projectionTextureMatrix;
  49772. },
  49773. enumerable: true,
  49774. configurable: true
  49775. });
  49776. ;
  49777. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49778. /**
  49779. * Gets the near clip of the Spotlight for texture projection.
  49780. */
  49781. get: function () {
  49782. return this._projectionTextureLightNear;
  49783. },
  49784. /**
  49785. * Sets the near clip of the Spotlight for texture projection.
  49786. */
  49787. set: function (value) {
  49788. this._projectionTextureLightNear = value;
  49789. this._projectionTextureProjectionLightDirty = true;
  49790. },
  49791. enumerable: true,
  49792. configurable: true
  49793. });
  49794. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49795. /**
  49796. * Gets the far clip of the Spotlight for texture projection.
  49797. */
  49798. get: function () {
  49799. return this._projectionTextureLightFar;
  49800. },
  49801. /**
  49802. * Sets the far clip of the Spotlight for texture projection.
  49803. */
  49804. set: function (value) {
  49805. this._projectionTextureLightFar = value;
  49806. this._projectionTextureProjectionLightDirty = true;
  49807. },
  49808. enumerable: true,
  49809. configurable: true
  49810. });
  49811. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49812. /**
  49813. * Gets the Up vector of the Spotlight for texture projection.
  49814. */
  49815. get: function () {
  49816. return this._projectionTextureUpDirection;
  49817. },
  49818. /**
  49819. * Sets the Up vector of the Spotlight for texture projection.
  49820. */
  49821. set: function (value) {
  49822. this._projectionTextureUpDirection = value;
  49823. this._projectionTextureProjectionLightDirty = true;
  49824. },
  49825. enumerable: true,
  49826. configurable: true
  49827. });
  49828. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49829. /**
  49830. * Gets the projection texture of the light.
  49831. */
  49832. get: function () {
  49833. return this._projectionTexture;
  49834. },
  49835. /**
  49836. * Sets the projection texture of the light.
  49837. */
  49838. set: function (value) {
  49839. this._projectionTexture = value;
  49840. this._projectionTextureDirty = true;
  49841. },
  49842. enumerable: true,
  49843. configurable: true
  49844. });
  49845. /**
  49846. * Returns the string "SpotLight".
  49847. * @returns the class name
  49848. */
  49849. SpotLight.prototype.getClassName = function () {
  49850. return "SpotLight";
  49851. };
  49852. /**
  49853. * Returns the integer 2.
  49854. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49855. */
  49856. SpotLight.prototype.getTypeID = function () {
  49857. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49858. };
  49859. /**
  49860. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49861. */
  49862. SpotLight.prototype._setDirection = function (value) {
  49863. _super.prototype._setDirection.call(this, value);
  49864. this._projectionTextureViewLightDirty = true;
  49865. };
  49866. /**
  49867. * Overrides the position setter to recompute the projection texture view light Matrix.
  49868. */
  49869. SpotLight.prototype._setPosition = function (value) {
  49870. _super.prototype._setPosition.call(this, value);
  49871. this._projectionTextureViewLightDirty = true;
  49872. };
  49873. /**
  49874. * 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.
  49875. * Returns the SpotLight.
  49876. */
  49877. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49878. var activeCamera = this.getScene().activeCamera;
  49879. if (!activeCamera) {
  49880. return;
  49881. }
  49882. this._shadowAngleScale = this._shadowAngleScale || 1;
  49883. var angle = this._shadowAngleScale * this._angle;
  49884. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49885. };
  49886. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49887. this._projectionTextureViewLightDirty = false;
  49888. this._projectionTextureDirty = true;
  49889. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49890. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49891. };
  49892. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49893. this._projectionTextureProjectionLightDirty = false;
  49894. this._projectionTextureDirty = true;
  49895. var light_far = this.projectionTextureLightFar;
  49896. var light_near = this.projectionTextureLightNear;
  49897. var P = light_far / (light_far - light_near);
  49898. var Q = -P * light_near;
  49899. var S = 1.0 / Math.tan(this._angle / 2.0);
  49900. var A = 1.0;
  49901. 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);
  49902. };
  49903. /**
  49904. * Main function for light texture projection matrix computing.
  49905. */
  49906. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49907. this._projectionTextureDirty = false;
  49908. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49909. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49910. };
  49911. SpotLight.prototype._buildUniformLayout = function () {
  49912. this._uniformBuffer.addUniform("vLightData", 4);
  49913. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49914. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49915. this._uniformBuffer.addUniform("vLightDirection", 3);
  49916. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49917. this._uniformBuffer.addUniform("depthValues", 2);
  49918. this._uniformBuffer.create();
  49919. };
  49920. /**
  49921. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49922. * @param effect The effect to update
  49923. * @param lightIndex The index of the light in the effect to update
  49924. * @returns The spot light
  49925. */
  49926. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49927. var normalizeDirection;
  49928. if (this.computeTransformedInformation()) {
  49929. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49930. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49931. }
  49932. else {
  49933. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49934. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49935. }
  49936. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49937. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49938. if (this._projectionTextureViewLightDirty) {
  49939. this._computeProjectionTextureViewLightMatrix();
  49940. }
  49941. if (this._projectionTextureProjectionLightDirty) {
  49942. this._computeProjectionTextureProjectionLightMatrix();
  49943. }
  49944. if (this._projectionTextureDirty) {
  49945. this._computeProjectionTextureMatrix();
  49946. }
  49947. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49948. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49949. }
  49950. return this;
  49951. };
  49952. /**
  49953. * Disposes the light and the associated resources.
  49954. */
  49955. SpotLight.prototype.dispose = function () {
  49956. _super.prototype.dispose.call(this);
  49957. if (this._projectionTexture) {
  49958. this._projectionTexture.dispose();
  49959. }
  49960. };
  49961. __decorate([
  49962. BABYLON.serialize()
  49963. ], SpotLight.prototype, "angle", null);
  49964. __decorate([
  49965. BABYLON.serialize()
  49966. ], SpotLight.prototype, "shadowAngleScale", null);
  49967. __decorate([
  49968. BABYLON.serialize()
  49969. ], SpotLight.prototype, "exponent", void 0);
  49970. __decorate([
  49971. BABYLON.serialize()
  49972. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49973. __decorate([
  49974. BABYLON.serialize()
  49975. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49976. __decorate([
  49977. BABYLON.serialize()
  49978. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49979. __decorate([
  49980. BABYLON.serializeAsTexture("projectedLightTexture")
  49981. ], SpotLight.prototype, "_projectionTexture", void 0);
  49982. return SpotLight;
  49983. }(BABYLON.ShadowLight));
  49984. BABYLON.SpotLight = SpotLight;
  49985. })(BABYLON || (BABYLON = {}));
  49986. //# sourceMappingURL=babylon.spotLight.js.map
  49987. var BABYLON;
  49988. (function (BABYLON) {
  49989. /**
  49990. * Class used to override all child animations of a given target
  49991. */
  49992. var AnimationPropertiesOverride = /** @class */ (function () {
  49993. function AnimationPropertiesOverride() {
  49994. /**
  49995. * Gets or sets a value indicating if animation blending must be used
  49996. */
  49997. this.enableBlending = false;
  49998. /**
  49999. * Gets or sets the blending speed to use when enableBlending is true
  50000. */
  50001. this.blendingSpeed = 0.01;
  50002. /**
  50003. * Gets or sets the default loop mode to use
  50004. */
  50005. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50006. }
  50007. return AnimationPropertiesOverride;
  50008. }());
  50009. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50010. })(BABYLON || (BABYLON = {}));
  50011. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50012. var BABYLON;
  50013. (function (BABYLON) {
  50014. /**
  50015. * Represents the range of an animation
  50016. */
  50017. var AnimationRange = /** @class */ (function () {
  50018. /**
  50019. * Initializes the range of an animation
  50020. * @param name The name of the animation range
  50021. * @param from The starting frame of the animation
  50022. * @param to The ending frame of the animation
  50023. */
  50024. function AnimationRange(
  50025. /**The name of the animation range**/
  50026. name,
  50027. /**The starting frame of the animation */
  50028. from,
  50029. /**The ending frame of the animation*/
  50030. to) {
  50031. this.name = name;
  50032. this.from = from;
  50033. this.to = to;
  50034. }
  50035. /**
  50036. * Makes a copy of the animation range
  50037. * @returns A copy of the animation range
  50038. */
  50039. AnimationRange.prototype.clone = function () {
  50040. return new AnimationRange(this.name, this.from, this.to);
  50041. };
  50042. return AnimationRange;
  50043. }());
  50044. BABYLON.AnimationRange = AnimationRange;
  50045. /**
  50046. * Composed of a frame, and an action function
  50047. */
  50048. var AnimationEvent = /** @class */ (function () {
  50049. /**
  50050. * Initializes the animation event
  50051. * @param frame The frame for which the event is triggered
  50052. * @param action The event to perform when triggered
  50053. * @param onlyOnce Specifies if the event should be triggered only once
  50054. */
  50055. function AnimationEvent(
  50056. /** The frame for which the event is triggered **/
  50057. frame,
  50058. /** The event to perform when triggered **/
  50059. action,
  50060. /** Specifies if the event should be triggered only once**/
  50061. onlyOnce) {
  50062. this.frame = frame;
  50063. this.action = action;
  50064. this.onlyOnce = onlyOnce;
  50065. /**
  50066. * Specifies if the animation event is done
  50067. */
  50068. this.isDone = false;
  50069. }
  50070. return AnimationEvent;
  50071. }());
  50072. BABYLON.AnimationEvent = AnimationEvent;
  50073. /**
  50074. * A cursor which tracks a point on a path
  50075. */
  50076. var PathCursor = /** @class */ (function () {
  50077. /**
  50078. * Initializes the path cursor
  50079. * @param path The path to track
  50080. */
  50081. function PathCursor(path) {
  50082. this.path = path;
  50083. /**
  50084. * Stores path cursor callbacks for when an onchange event is triggered
  50085. */
  50086. this._onchange = new Array();
  50087. /**
  50088. * The value of the path cursor
  50089. */
  50090. this.value = 0;
  50091. /**
  50092. * The animation array of the path cursor
  50093. */
  50094. this.animations = new Array();
  50095. }
  50096. /**
  50097. * Gets the cursor point on the path
  50098. * @returns A point on the path cursor at the cursor location
  50099. */
  50100. PathCursor.prototype.getPoint = function () {
  50101. var point = this.path.getPointAtLengthPosition(this.value);
  50102. return new BABYLON.Vector3(point.x, 0, point.y);
  50103. };
  50104. /**
  50105. * Moves the cursor ahead by the step amount
  50106. * @param step The amount to move the cursor forward
  50107. * @returns This path cursor
  50108. */
  50109. PathCursor.prototype.moveAhead = function (step) {
  50110. if (step === void 0) { step = 0.002; }
  50111. this.move(step);
  50112. return this;
  50113. };
  50114. /**
  50115. * Moves the cursor behind by the step amount
  50116. * @param step The amount to move the cursor back
  50117. * @returns This path cursor
  50118. */
  50119. PathCursor.prototype.moveBack = function (step) {
  50120. if (step === void 0) { step = 0.002; }
  50121. this.move(-step);
  50122. return this;
  50123. };
  50124. /**
  50125. * Moves the cursor by the step amount
  50126. * If the step amount is greater than one, an exception is thrown
  50127. * @param step The amount to move the cursor
  50128. * @returns This path cursor
  50129. */
  50130. PathCursor.prototype.move = function (step) {
  50131. if (Math.abs(step) > 1) {
  50132. throw "step size should be less than 1.";
  50133. }
  50134. this.value += step;
  50135. this.ensureLimits();
  50136. this.raiseOnChange();
  50137. return this;
  50138. };
  50139. /**
  50140. * Ensures that the value is limited between zero and one
  50141. * @returns This path cursor
  50142. */
  50143. PathCursor.prototype.ensureLimits = function () {
  50144. while (this.value > 1) {
  50145. this.value -= 1;
  50146. }
  50147. while (this.value < 0) {
  50148. this.value += 1;
  50149. }
  50150. return this;
  50151. };
  50152. /**
  50153. * Runs onchange callbacks on change (used by the animation engine)
  50154. * @returns This path cursor
  50155. */
  50156. PathCursor.prototype.raiseOnChange = function () {
  50157. var _this = this;
  50158. this._onchange.forEach(function (f) { return f(_this); });
  50159. return this;
  50160. };
  50161. /**
  50162. * Executes a function on change
  50163. * @param f A path cursor onchange callback
  50164. * @returns This path cursor
  50165. */
  50166. PathCursor.prototype.onchange = function (f) {
  50167. this._onchange.push(f);
  50168. return this;
  50169. };
  50170. return PathCursor;
  50171. }());
  50172. BABYLON.PathCursor = PathCursor;
  50173. /**
  50174. * Enum for the animation key frame interpolation type
  50175. */
  50176. var AnimationKeyInterpolation;
  50177. (function (AnimationKeyInterpolation) {
  50178. /**
  50179. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50180. */
  50181. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50182. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50183. /**
  50184. * Class used to store any kind of animation
  50185. */
  50186. var Animation = /** @class */ (function () {
  50187. /**
  50188. * Initializes the animation
  50189. * @param name Name of the animation
  50190. * @param targetProperty Property to animate
  50191. * @param framePerSecond The frames per second of the animation
  50192. * @param dataType The data type of the animation
  50193. * @param loopMode The loop mode of the animation
  50194. * @param enableBlendings Specifies if blending should be enabled
  50195. */
  50196. function Animation(
  50197. /**Name of the animation */
  50198. name,
  50199. /**Property to animate */
  50200. targetProperty,
  50201. /**The frames per second of the animation */
  50202. framePerSecond,
  50203. /**The data type of the animation */
  50204. dataType,
  50205. /**The loop mode of the animation */
  50206. loopMode,
  50207. /**Specifies if blending should be enabled */
  50208. enableBlending) {
  50209. this.name = name;
  50210. this.targetProperty = targetProperty;
  50211. this.framePerSecond = framePerSecond;
  50212. this.dataType = dataType;
  50213. this.loopMode = loopMode;
  50214. this.enableBlending = enableBlending;
  50215. /**
  50216. * @hidden Internal use only
  50217. */
  50218. this._runtimeAnimations = new Array();
  50219. /**
  50220. * The set of event that will be linked to this animation
  50221. */
  50222. this._events = new Array();
  50223. /**
  50224. * Stores the blending speed of the animation
  50225. */
  50226. this.blendingSpeed = 0.01;
  50227. /**
  50228. * Stores the animation ranges for the animation
  50229. */
  50230. this._ranges = {};
  50231. this.targetPropertyPath = targetProperty.split(".");
  50232. this.dataType = dataType;
  50233. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50234. }
  50235. /**
  50236. * @hidden Internal use
  50237. */
  50238. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50239. var dataType = undefined;
  50240. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50241. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50242. }
  50243. else if (from instanceof BABYLON.Quaternion) {
  50244. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50245. }
  50246. else if (from instanceof BABYLON.Vector3) {
  50247. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50248. }
  50249. else if (from instanceof BABYLON.Vector2) {
  50250. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50251. }
  50252. else if (from instanceof BABYLON.Color3) {
  50253. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50254. }
  50255. else if (from instanceof BABYLON.Size) {
  50256. dataType = Animation.ANIMATIONTYPE_SIZE;
  50257. }
  50258. if (dataType == undefined) {
  50259. return null;
  50260. }
  50261. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50262. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50263. animation.setKeys(keys);
  50264. if (easingFunction !== undefined) {
  50265. animation.setEasingFunction(easingFunction);
  50266. }
  50267. return animation;
  50268. };
  50269. /**
  50270. * Sets up an animation
  50271. * @param property The property to animate
  50272. * @param animationType The animation type to apply
  50273. * @param framePerSecond The frames per second of the animation
  50274. * @param easingFunction The easing function used in the animation
  50275. * @returns The created animation
  50276. */
  50277. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50278. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50279. animation.setEasingFunction(easingFunction);
  50280. return animation;
  50281. };
  50282. /**
  50283. * Create and start an animation on a node
  50284. * @param name defines the name of the global animation that will be run on all nodes
  50285. * @param node defines the root node where the animation will take place
  50286. * @param targetProperty defines property to animate
  50287. * @param framePerSecond defines the number of frame per second yo use
  50288. * @param totalFrame defines the number of frames in total
  50289. * @param from defines the initial value
  50290. * @param to defines the final value
  50291. * @param loopMode defines which loop mode you want to use (off by default)
  50292. * @param easingFunction defines the easing function to use (linear by default)
  50293. * @param onAnimationEnd defines the callback to call when animation end
  50294. * @returns the animatable created for this animation
  50295. */
  50296. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50297. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50298. if (!animation) {
  50299. return null;
  50300. }
  50301. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50302. };
  50303. /**
  50304. * Create and start an animation on a node and its descendants
  50305. * @param name defines the name of the global animation that will be run on all nodes
  50306. * @param node defines the root node where the animation will take place
  50307. * @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
  50308. * @param targetProperty defines property to animate
  50309. * @param framePerSecond defines the number of frame per second to use
  50310. * @param totalFrame defines the number of frames in total
  50311. * @param from defines the initial value
  50312. * @param to defines the final value
  50313. * @param loopMode defines which loop mode you want to use (off by default)
  50314. * @param easingFunction defines the easing function to use (linear by default)
  50315. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50316. * @returns the list of animatables created for all nodes
  50317. * @example https://www.babylonjs-playground.com/#MH0VLI
  50318. */
  50319. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50320. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50321. if (!animation) {
  50322. return null;
  50323. }
  50324. var scene = node.getScene();
  50325. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50326. };
  50327. /**
  50328. * Creates a new animation, merges it with the existing animations and starts it
  50329. * @param name Name of the animation
  50330. * @param node Node which contains the scene that begins the animations
  50331. * @param targetProperty Specifies which property to animate
  50332. * @param framePerSecond The frames per second of the animation
  50333. * @param totalFrame The total number of frames
  50334. * @param from The frame at the beginning of the animation
  50335. * @param to The frame at the end of the animation
  50336. * @param loopMode Specifies the loop mode of the animation
  50337. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50338. * @param onAnimationEnd Callback to run once the animation is complete
  50339. * @returns Nullable animation
  50340. */
  50341. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50342. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50343. if (!animation) {
  50344. return null;
  50345. }
  50346. node.animations.push(animation);
  50347. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50348. };
  50349. /**
  50350. * Transition property of the Camera to the target Value
  50351. * @param property The property to transition
  50352. * @param targetValue The target Value of the property
  50353. * @param host The object where the property to animate belongs
  50354. * @param scene Scene used to run the animation
  50355. * @param frameRate Framerate (in frame/s) to use
  50356. * @param transition The transition type we want to use
  50357. * @param duration The duration of the animation, in milliseconds
  50358. * @param onAnimationEnd Callback trigger at the end of the animation
  50359. * @returns Nullable animation
  50360. */
  50361. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50362. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50363. if (duration <= 0) {
  50364. host[property] = targetValue;
  50365. if (onAnimationEnd) {
  50366. onAnimationEnd();
  50367. }
  50368. return null;
  50369. }
  50370. var endFrame = frameRate * (duration / 1000);
  50371. transition.setKeys([{
  50372. frame: 0,
  50373. value: host[property].clone ? host[property].clone() : host[property]
  50374. },
  50375. {
  50376. frame: endFrame,
  50377. value: targetValue
  50378. }]);
  50379. if (!host.animations) {
  50380. host.animations = [];
  50381. }
  50382. host.animations.push(transition);
  50383. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50384. animation.onAnimationEnd = onAnimationEnd;
  50385. return animation;
  50386. };
  50387. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50388. /**
  50389. * Return the array of runtime animations currently using this animation
  50390. */
  50391. get: function () {
  50392. return this._runtimeAnimations;
  50393. },
  50394. enumerable: true,
  50395. configurable: true
  50396. });
  50397. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50398. /**
  50399. * Specifies if any of the runtime animations are currently running
  50400. */
  50401. get: function () {
  50402. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50403. var runtimeAnimation = _a[_i];
  50404. if (!runtimeAnimation.isStopped) {
  50405. return true;
  50406. }
  50407. }
  50408. return false;
  50409. },
  50410. enumerable: true,
  50411. configurable: true
  50412. });
  50413. // Methods
  50414. /**
  50415. * Converts the animation to a string
  50416. * @param fullDetails support for multiple levels of logging within scene loading
  50417. * @returns String form of the animation
  50418. */
  50419. Animation.prototype.toString = function (fullDetails) {
  50420. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50421. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50422. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50423. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50424. if (fullDetails) {
  50425. ret += ", Ranges: {";
  50426. var first = true;
  50427. for (var name in this._ranges) {
  50428. if (first) {
  50429. ret += ", ";
  50430. first = false;
  50431. }
  50432. ret += name;
  50433. }
  50434. ret += "}";
  50435. }
  50436. return ret;
  50437. };
  50438. /**
  50439. * Add an event to this animation
  50440. * @param event Event to add
  50441. */
  50442. Animation.prototype.addEvent = function (event) {
  50443. this._events.push(event);
  50444. };
  50445. /**
  50446. * Remove all events found at the given frame
  50447. * @param frame The frame to remove events from
  50448. */
  50449. Animation.prototype.removeEvents = function (frame) {
  50450. for (var index = 0; index < this._events.length; index++) {
  50451. if (this._events[index].frame === frame) {
  50452. this._events.splice(index, 1);
  50453. index--;
  50454. }
  50455. }
  50456. };
  50457. /**
  50458. * Retrieves all the events from the animation
  50459. * @returns Events from the animation
  50460. */
  50461. Animation.prototype.getEvents = function () {
  50462. return this._events;
  50463. };
  50464. /**
  50465. * Creates an animation range
  50466. * @param name Name of the animation range
  50467. * @param from Starting frame of the animation range
  50468. * @param to Ending frame of the animation
  50469. */
  50470. Animation.prototype.createRange = function (name, from, to) {
  50471. // check name not already in use; could happen for bones after serialized
  50472. if (!this._ranges[name]) {
  50473. this._ranges[name] = new AnimationRange(name, from, to);
  50474. }
  50475. };
  50476. /**
  50477. * Deletes an animation range by name
  50478. * @param name Name of the animation range to delete
  50479. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50480. */
  50481. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50482. if (deleteFrames === void 0) { deleteFrames = true; }
  50483. var range = this._ranges[name];
  50484. if (!range) {
  50485. return;
  50486. }
  50487. if (deleteFrames) {
  50488. var from = range.from;
  50489. var to = range.to;
  50490. // this loop MUST go high to low for multiple splices to work
  50491. for (var key = this._keys.length - 1; key >= 0; key--) {
  50492. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50493. this._keys.splice(key, 1);
  50494. }
  50495. }
  50496. }
  50497. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50498. };
  50499. /**
  50500. * Gets the animation range by name, or null if not defined
  50501. * @param name Name of the animation range
  50502. * @returns Nullable animation range
  50503. */
  50504. Animation.prototype.getRange = function (name) {
  50505. return this._ranges[name];
  50506. };
  50507. /**
  50508. * Gets the key frames from the animation
  50509. * @returns The key frames of the animation
  50510. */
  50511. Animation.prototype.getKeys = function () {
  50512. return this._keys;
  50513. };
  50514. /**
  50515. * Gets the highest frame rate of the animation
  50516. * @returns Highest frame rate of the animation
  50517. */
  50518. Animation.prototype.getHighestFrame = function () {
  50519. var ret = 0;
  50520. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50521. if (ret < this._keys[key].frame) {
  50522. ret = this._keys[key].frame;
  50523. }
  50524. }
  50525. return ret;
  50526. };
  50527. /**
  50528. * Gets the easing function of the animation
  50529. * @returns Easing function of the animation
  50530. */
  50531. Animation.prototype.getEasingFunction = function () {
  50532. return this._easingFunction;
  50533. };
  50534. /**
  50535. * Sets the easing function of the animation
  50536. * @param easingFunction A custom mathematical formula for animation
  50537. */
  50538. Animation.prototype.setEasingFunction = function (easingFunction) {
  50539. this._easingFunction = easingFunction;
  50540. };
  50541. /**
  50542. * Interpolates a scalar linearly
  50543. * @param startValue Start value of the animation curve
  50544. * @param endValue End value of the animation curve
  50545. * @param gradient Scalar amount to interpolate
  50546. * @returns Interpolated scalar value
  50547. */
  50548. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50549. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50550. };
  50551. /**
  50552. * Interpolates a scalar cubically
  50553. * @param startValue Start value of the animation curve
  50554. * @param outTangent End tangent of the animation
  50555. * @param endValue End value of the animation curve
  50556. * @param inTangent Start tangent of the animation curve
  50557. * @param gradient Scalar amount to interpolate
  50558. * @returns Interpolated scalar value
  50559. */
  50560. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50561. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50562. };
  50563. /**
  50564. * Interpolates a quaternion using a spherical linear interpolation
  50565. * @param startValue Start value of the animation curve
  50566. * @param endValue End value of the animation curve
  50567. * @param gradient Scalar amount to interpolate
  50568. * @returns Interpolated quaternion value
  50569. */
  50570. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50571. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50572. };
  50573. /**
  50574. * Interpolates a quaternion cubically
  50575. * @param startValue Start value of the animation curve
  50576. * @param outTangent End tangent of the animation curve
  50577. * @param endValue End value of the animation curve
  50578. * @param inTangent Start tangent of the animation curve
  50579. * @param gradient Scalar amount to interpolate
  50580. * @returns Interpolated quaternion value
  50581. */
  50582. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50583. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50584. };
  50585. /**
  50586. * Interpolates a Vector3 linearl
  50587. * @param startValue Start value of the animation curve
  50588. * @param endValue End value of the animation curve
  50589. * @param gradient Scalar amount to interpolate
  50590. * @returns Interpolated scalar value
  50591. */
  50592. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50593. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50594. };
  50595. /**
  50596. * Interpolates a Vector3 cubically
  50597. * @param startValue Start value of the animation curve
  50598. * @param outTangent End tangent of the animation
  50599. * @param endValue End value of the animation curve
  50600. * @param inTangent Start tangent of the animation curve
  50601. * @param gradient Scalar amount to interpolate
  50602. * @returns InterpolatedVector3 value
  50603. */
  50604. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50605. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50606. };
  50607. /**
  50608. * Interpolates a Vector2 linearly
  50609. * @param startValue Start value of the animation curve
  50610. * @param endValue End value of the animation curve
  50611. * @param gradient Scalar amount to interpolate
  50612. * @returns Interpolated Vector2 value
  50613. */
  50614. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50615. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50616. };
  50617. /**
  50618. * Interpolates a Vector2 cubically
  50619. * @param startValue Start value of the animation curve
  50620. * @param outTangent End tangent of the animation
  50621. * @param endValue End value of the animation curve
  50622. * @param inTangent Start tangent of the animation curve
  50623. * @param gradient Scalar amount to interpolate
  50624. * @returns Interpolated Vector2 value
  50625. */
  50626. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50627. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50628. };
  50629. /**
  50630. * Interpolates a size linearly
  50631. * @param startValue Start value of the animation curve
  50632. * @param endValue End value of the animation curve
  50633. * @param gradient Scalar amount to interpolate
  50634. * @returns Interpolated Size value
  50635. */
  50636. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50637. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50638. };
  50639. /**
  50640. * Interpolates a Color3 linearly
  50641. * @param startValue Start value of the animation curve
  50642. * @param endValue End value of the animation curve
  50643. * @param gradient Scalar amount to interpolate
  50644. * @returns Interpolated Color3 value
  50645. */
  50646. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50647. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50648. };
  50649. /**
  50650. * @hidden Internal use only
  50651. */
  50652. Animation.prototype._getKeyValue = function (value) {
  50653. if (typeof value === "function") {
  50654. return value();
  50655. }
  50656. return value;
  50657. };
  50658. /**
  50659. * @hidden Internal use only
  50660. */
  50661. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50662. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50663. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50664. }
  50665. var keys = this.getKeys();
  50666. // Try to get a hash to find the right key
  50667. 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));
  50668. if (keys[startKeyIndex].frame >= currentFrame) {
  50669. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50670. startKeyIndex--;
  50671. }
  50672. }
  50673. for (var key = startKeyIndex; key < keys.length; key++) {
  50674. var endKey = keys[key + 1];
  50675. if (endKey.frame >= currentFrame) {
  50676. var startKey = keys[key];
  50677. var startValue = this._getKeyValue(startKey.value);
  50678. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50679. return startValue;
  50680. }
  50681. var endValue = this._getKeyValue(endKey.value);
  50682. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50683. var frameDelta = endKey.frame - startKey.frame;
  50684. // gradient : percent of currentFrame between the frame inf and the frame sup
  50685. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50686. // check for easingFunction and correction of gradient
  50687. var easingFunction = this.getEasingFunction();
  50688. if (easingFunction != null) {
  50689. gradient = easingFunction.ease(gradient);
  50690. }
  50691. switch (this.dataType) {
  50692. // Float
  50693. case Animation.ANIMATIONTYPE_FLOAT:
  50694. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50695. switch (loopMode) {
  50696. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50697. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50698. return floatValue;
  50699. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50700. return offsetValue * repeatCount + floatValue;
  50701. }
  50702. break;
  50703. // Quaternion
  50704. case Animation.ANIMATIONTYPE_QUATERNION:
  50705. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50706. switch (loopMode) {
  50707. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50708. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50709. return quatValue;
  50710. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50711. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50712. }
  50713. return quatValue;
  50714. // Vector3
  50715. case Animation.ANIMATIONTYPE_VECTOR3:
  50716. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50717. switch (loopMode) {
  50718. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50719. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50720. return vec3Value;
  50721. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50722. return vec3Value.add(offsetValue.scale(repeatCount));
  50723. }
  50724. // Vector2
  50725. case Animation.ANIMATIONTYPE_VECTOR2:
  50726. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50727. switch (loopMode) {
  50728. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50729. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50730. return vec2Value;
  50731. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50732. return vec2Value.add(offsetValue.scale(repeatCount));
  50733. }
  50734. // Size
  50735. case Animation.ANIMATIONTYPE_SIZE:
  50736. switch (loopMode) {
  50737. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50738. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50739. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50740. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50741. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50742. }
  50743. // Color3
  50744. case Animation.ANIMATIONTYPE_COLOR3:
  50745. switch (loopMode) {
  50746. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50747. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50748. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50749. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50750. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50751. }
  50752. // Matrix
  50753. case Animation.ANIMATIONTYPE_MATRIX:
  50754. switch (loopMode) {
  50755. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50756. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50757. if (Animation.AllowMatricesInterpolation) {
  50758. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50759. }
  50760. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50761. return startValue;
  50762. }
  50763. default:
  50764. break;
  50765. }
  50766. break;
  50767. }
  50768. }
  50769. return this._getKeyValue(keys[keys.length - 1].value);
  50770. };
  50771. /**
  50772. * Defines the function to use to interpolate matrices
  50773. * @param startValue defines the start matrix
  50774. * @param endValue defines the end matrix
  50775. * @param gradient defines the gradient between both matrices
  50776. * @param result defines an optional target matrix where to store the interpolation
  50777. * @returns the interpolated matrix
  50778. */
  50779. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50780. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50781. if (result) {
  50782. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50783. return result;
  50784. }
  50785. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50786. }
  50787. if (result) {
  50788. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50789. return result;
  50790. }
  50791. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50792. };
  50793. /**
  50794. * Makes a copy of the animation
  50795. * @returns Cloned animation
  50796. */
  50797. Animation.prototype.clone = function () {
  50798. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50799. clone.enableBlending = this.enableBlending;
  50800. clone.blendingSpeed = this.blendingSpeed;
  50801. if (this._keys) {
  50802. clone.setKeys(this._keys);
  50803. }
  50804. if (this._ranges) {
  50805. clone._ranges = {};
  50806. for (var name in this._ranges) {
  50807. var range = this._ranges[name];
  50808. if (!range) {
  50809. continue;
  50810. }
  50811. clone._ranges[name] = range.clone();
  50812. }
  50813. }
  50814. return clone;
  50815. };
  50816. /**
  50817. * Sets the key frames of the animation
  50818. * @param values The animation key frames to set
  50819. */
  50820. Animation.prototype.setKeys = function (values) {
  50821. this._keys = values.slice(0);
  50822. };
  50823. /**
  50824. * Serializes the animation to an object
  50825. * @returns Serialized object
  50826. */
  50827. Animation.prototype.serialize = function () {
  50828. var serializationObject = {};
  50829. serializationObject.name = this.name;
  50830. serializationObject.property = this.targetProperty;
  50831. serializationObject.framePerSecond = this.framePerSecond;
  50832. serializationObject.dataType = this.dataType;
  50833. serializationObject.loopBehavior = this.loopMode;
  50834. serializationObject.enableBlending = this.enableBlending;
  50835. serializationObject.blendingSpeed = this.blendingSpeed;
  50836. var dataType = this.dataType;
  50837. serializationObject.keys = [];
  50838. var keys = this.getKeys();
  50839. for (var index = 0; index < keys.length; index++) {
  50840. var animationKey = keys[index];
  50841. var key = {};
  50842. key.frame = animationKey.frame;
  50843. switch (dataType) {
  50844. case Animation.ANIMATIONTYPE_FLOAT:
  50845. key.values = [animationKey.value];
  50846. break;
  50847. case Animation.ANIMATIONTYPE_QUATERNION:
  50848. case Animation.ANIMATIONTYPE_MATRIX:
  50849. case Animation.ANIMATIONTYPE_VECTOR3:
  50850. case Animation.ANIMATIONTYPE_COLOR3:
  50851. key.values = animationKey.value.asArray();
  50852. break;
  50853. }
  50854. serializationObject.keys.push(key);
  50855. }
  50856. serializationObject.ranges = [];
  50857. for (var name in this._ranges) {
  50858. var source = this._ranges[name];
  50859. if (!source) {
  50860. continue;
  50861. }
  50862. var range = {};
  50863. range.name = name;
  50864. range.from = source.from;
  50865. range.to = source.to;
  50866. serializationObject.ranges.push(range);
  50867. }
  50868. return serializationObject;
  50869. };
  50870. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50871. /**
  50872. * Get the float animation type
  50873. */
  50874. get: function () {
  50875. return Animation._ANIMATIONTYPE_FLOAT;
  50876. },
  50877. enumerable: true,
  50878. configurable: true
  50879. });
  50880. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50881. /**
  50882. * Get the Vector3 animation type
  50883. */
  50884. get: function () {
  50885. return Animation._ANIMATIONTYPE_VECTOR3;
  50886. },
  50887. enumerable: true,
  50888. configurable: true
  50889. });
  50890. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50891. /**
  50892. * Get the Vectpr2 animation type
  50893. */
  50894. get: function () {
  50895. return Animation._ANIMATIONTYPE_VECTOR2;
  50896. },
  50897. enumerable: true,
  50898. configurable: true
  50899. });
  50900. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50901. /**
  50902. * Get the Size animation type
  50903. */
  50904. get: function () {
  50905. return Animation._ANIMATIONTYPE_SIZE;
  50906. },
  50907. enumerable: true,
  50908. configurable: true
  50909. });
  50910. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50911. /**
  50912. * Get the Quaternion animation type
  50913. */
  50914. get: function () {
  50915. return Animation._ANIMATIONTYPE_QUATERNION;
  50916. },
  50917. enumerable: true,
  50918. configurable: true
  50919. });
  50920. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50921. /**
  50922. * Get the Matrix animation type
  50923. */
  50924. get: function () {
  50925. return Animation._ANIMATIONTYPE_MATRIX;
  50926. },
  50927. enumerable: true,
  50928. configurable: true
  50929. });
  50930. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50931. /**
  50932. * Get the Color3 animation type
  50933. */
  50934. get: function () {
  50935. return Animation._ANIMATIONTYPE_COLOR3;
  50936. },
  50937. enumerable: true,
  50938. configurable: true
  50939. });
  50940. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50941. /**
  50942. * Get the Relative Loop Mode
  50943. */
  50944. get: function () {
  50945. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50951. /**
  50952. * Get the Cycle Loop Mode
  50953. */
  50954. get: function () {
  50955. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50956. },
  50957. enumerable: true,
  50958. configurable: true
  50959. });
  50960. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50961. /**
  50962. * Get the Constant Loop Mode
  50963. */
  50964. get: function () {
  50965. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50966. },
  50967. enumerable: true,
  50968. configurable: true
  50969. });
  50970. /**
  50971. * Parses an animation object and creates an animation
  50972. * @param parsedAnimation Parsed animation object
  50973. * @returns Animation object
  50974. */
  50975. Animation.Parse = function (parsedAnimation) {
  50976. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50977. var dataType = parsedAnimation.dataType;
  50978. var keys = [];
  50979. var data;
  50980. var index;
  50981. if (parsedAnimation.enableBlending) {
  50982. animation.enableBlending = parsedAnimation.enableBlending;
  50983. }
  50984. if (parsedAnimation.blendingSpeed) {
  50985. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50986. }
  50987. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50988. var key = parsedAnimation.keys[index];
  50989. var inTangent;
  50990. var outTangent;
  50991. switch (dataType) {
  50992. case Animation.ANIMATIONTYPE_FLOAT:
  50993. data = key.values[0];
  50994. if (key.values.length >= 1) {
  50995. inTangent = key.values[1];
  50996. }
  50997. if (key.values.length >= 2) {
  50998. outTangent = key.values[2];
  50999. }
  51000. break;
  51001. case Animation.ANIMATIONTYPE_QUATERNION:
  51002. data = BABYLON.Quaternion.FromArray(key.values);
  51003. if (key.values.length >= 8) {
  51004. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51005. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51006. inTangent = _inTangent;
  51007. }
  51008. }
  51009. if (key.values.length >= 12) {
  51010. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51011. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51012. outTangent = _outTangent;
  51013. }
  51014. }
  51015. break;
  51016. case Animation.ANIMATIONTYPE_MATRIX:
  51017. data = BABYLON.Matrix.FromArray(key.values);
  51018. break;
  51019. case Animation.ANIMATIONTYPE_COLOR3:
  51020. data = BABYLON.Color3.FromArray(key.values);
  51021. break;
  51022. case Animation.ANIMATIONTYPE_VECTOR3:
  51023. default:
  51024. data = BABYLON.Vector3.FromArray(key.values);
  51025. break;
  51026. }
  51027. var keyData = {};
  51028. keyData.frame = key.frame;
  51029. keyData.value = data;
  51030. if (inTangent != undefined) {
  51031. keyData.inTangent = inTangent;
  51032. }
  51033. if (outTangent != undefined) {
  51034. keyData.outTangent = outTangent;
  51035. }
  51036. keys.push(keyData);
  51037. }
  51038. animation.setKeys(keys);
  51039. if (parsedAnimation.ranges) {
  51040. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51041. data = parsedAnimation.ranges[index];
  51042. animation.createRange(data.name, data.from, data.to);
  51043. }
  51044. }
  51045. return animation;
  51046. };
  51047. /**
  51048. * Appends the serialized animations from the source animations
  51049. * @param source Source containing the animations
  51050. * @param destination Target to store the animations
  51051. */
  51052. Animation.AppendSerializedAnimations = function (source, destination) {
  51053. if (source.animations) {
  51054. destination.animations = [];
  51055. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51056. var animation = source.animations[animationIndex];
  51057. destination.animations.push(animation.serialize());
  51058. }
  51059. }
  51060. };
  51061. /**
  51062. * Use matrix interpolation instead of using direct key value when animating matrices
  51063. */
  51064. Animation.AllowMatricesInterpolation = false;
  51065. /**
  51066. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51067. */
  51068. Animation.AllowMatrixDecomposeForInterpolation = true;
  51069. // Statics
  51070. /**
  51071. * Float animation type
  51072. */
  51073. Animation._ANIMATIONTYPE_FLOAT = 0;
  51074. /**
  51075. * Vector3 animation type
  51076. */
  51077. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51078. /**
  51079. * Quaternion animation type
  51080. */
  51081. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51082. /**
  51083. * Matrix animation type
  51084. */
  51085. Animation._ANIMATIONTYPE_MATRIX = 3;
  51086. /**
  51087. * Color3 animation type
  51088. */
  51089. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51090. /**
  51091. * Vector2 animation type
  51092. */
  51093. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51094. /**
  51095. * Size animation type
  51096. */
  51097. Animation._ANIMATIONTYPE_SIZE = 6;
  51098. /**
  51099. * Relative Loop Mode
  51100. */
  51101. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51102. /**
  51103. * Cycle Loop Mode
  51104. */
  51105. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51106. /**
  51107. * Constant Loop Mode
  51108. */
  51109. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51110. return Animation;
  51111. }());
  51112. BABYLON.Animation = Animation;
  51113. })(BABYLON || (BABYLON = {}));
  51114. //# sourceMappingURL=babylon.animation.js.map
  51115. var BABYLON;
  51116. (function (BABYLON) {
  51117. /**
  51118. * This class defines the direct association between an animation and a target
  51119. */
  51120. var TargetedAnimation = /** @class */ (function () {
  51121. function TargetedAnimation() {
  51122. }
  51123. return TargetedAnimation;
  51124. }());
  51125. BABYLON.TargetedAnimation = TargetedAnimation;
  51126. /**
  51127. * Use this class to create coordinated animations on multiple targets
  51128. */
  51129. var AnimationGroup = /** @class */ (function () {
  51130. function AnimationGroup(name, scene) {
  51131. if (scene === void 0) { scene = null; }
  51132. this.name = name;
  51133. this._targetedAnimations = new Array();
  51134. this._animatables = new Array();
  51135. this._from = Number.MAX_VALUE;
  51136. this._to = -Number.MAX_VALUE;
  51137. this._speedRatio = 1;
  51138. this.onAnimationEndObservable = new BABYLON.Observable();
  51139. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51140. this._scene.animationGroups.push(this);
  51141. }
  51142. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51143. /**
  51144. * Define if the animations are started
  51145. */
  51146. get: function () {
  51147. return this._isStarted;
  51148. },
  51149. enumerable: true,
  51150. configurable: true
  51151. });
  51152. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51153. /**
  51154. * Gets or sets the speed ratio to use for all animations
  51155. */
  51156. get: function () {
  51157. return this._speedRatio;
  51158. },
  51159. /**
  51160. * Gets or sets the speed ratio to use for all animations
  51161. */
  51162. set: function (value) {
  51163. if (this._speedRatio === value) {
  51164. return;
  51165. }
  51166. this._speedRatio = value;
  51167. for (var index = 0; index < this._animatables.length; index++) {
  51168. var animatable = this._animatables[index];
  51169. animatable.speedRatio = this._speedRatio;
  51170. }
  51171. },
  51172. enumerable: true,
  51173. configurable: true
  51174. });
  51175. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51176. /**
  51177. * Gets the targeted animations for this animation group
  51178. */
  51179. get: function () {
  51180. return this._targetedAnimations;
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51186. /**
  51187. * returning the list of animatables controlled by this animation group.
  51188. */
  51189. get: function () {
  51190. return this._animatables;
  51191. },
  51192. enumerable: true,
  51193. configurable: true
  51194. });
  51195. /**
  51196. * Add an animation (with its target) in the group
  51197. * @param animation defines the animation we want to add
  51198. * @param target defines the target of the animation
  51199. * @returns the {BABYLON.TargetedAnimation} object
  51200. */
  51201. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51202. var targetedAnimation = {
  51203. animation: animation,
  51204. target: target
  51205. };
  51206. var keys = animation.getKeys();
  51207. if (this._from > keys[0].frame) {
  51208. this._from = keys[0].frame;
  51209. }
  51210. if (this._to < keys[keys.length - 1].frame) {
  51211. this._to = keys[keys.length - 1].frame;
  51212. }
  51213. this._targetedAnimations.push(targetedAnimation);
  51214. return targetedAnimation;
  51215. };
  51216. /**
  51217. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51218. * It can add constant keys at begin or end
  51219. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51220. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51221. */
  51222. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51223. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51224. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51225. beginFrame = Math.max(beginFrame, this._from);
  51226. endFrame = Math.min(endFrame, this._to);
  51227. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51228. var targetedAnimation = this._targetedAnimations[index];
  51229. var keys = targetedAnimation.animation.getKeys();
  51230. var startKey = keys[0];
  51231. var endKey = keys[keys.length - 1];
  51232. if (startKey.frame > beginFrame) {
  51233. var newKey = {
  51234. frame: beginFrame,
  51235. value: startKey.value,
  51236. inTangent: startKey.inTangent,
  51237. outTangent: startKey.outTangent,
  51238. interpolation: startKey.interpolation
  51239. };
  51240. keys.splice(0, 0, newKey);
  51241. }
  51242. if (endKey.frame < endFrame) {
  51243. var newKey = {
  51244. frame: endFrame,
  51245. value: endKey.value,
  51246. inTangent: endKey.outTangent,
  51247. outTangent: endKey.outTangent,
  51248. interpolation: endKey.interpolation
  51249. };
  51250. keys.push(newKey);
  51251. }
  51252. }
  51253. return this;
  51254. };
  51255. /**
  51256. * Start all animations on given targets
  51257. * @param loop defines if animations must loop
  51258. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51259. * @param from defines the from key (optional)
  51260. * @param to defines the to key (optional)
  51261. * @returns the current animation group
  51262. */
  51263. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51264. var _this = this;
  51265. if (loop === void 0) { loop = false; }
  51266. if (speedRatio === void 0) { speedRatio = 1; }
  51267. if (this._isStarted || this._targetedAnimations.length === 0) {
  51268. return this;
  51269. }
  51270. var _loop_1 = function (targetedAnimation) {
  51271. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51272. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51273. }));
  51274. };
  51275. var this_1 = this;
  51276. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51277. var targetedAnimation = _a[_i];
  51278. _loop_1(targetedAnimation);
  51279. }
  51280. this._speedRatio = speedRatio;
  51281. this._isStarted = true;
  51282. return this;
  51283. };
  51284. /**
  51285. * Pause all animations
  51286. */
  51287. AnimationGroup.prototype.pause = function () {
  51288. if (!this._isStarted) {
  51289. return this;
  51290. }
  51291. for (var index = 0; index < this._animatables.length; index++) {
  51292. var animatable = this._animatables[index];
  51293. animatable.pause();
  51294. }
  51295. return this;
  51296. };
  51297. /**
  51298. * Play all animations to initial state
  51299. * This function will start() the animations if they were not started or will restart() them if they were paused
  51300. * @param loop defines if animations must loop
  51301. */
  51302. AnimationGroup.prototype.play = function (loop) {
  51303. if (this.isStarted) {
  51304. if (loop !== undefined) {
  51305. for (var index = 0; index < this._animatables.length; index++) {
  51306. var animatable = this._animatables[index];
  51307. animatable.loopAnimation = loop;
  51308. }
  51309. }
  51310. this.restart();
  51311. }
  51312. else {
  51313. this.start(loop, this._speedRatio);
  51314. }
  51315. return this;
  51316. };
  51317. /**
  51318. * Reset all animations to initial state
  51319. */
  51320. AnimationGroup.prototype.reset = function () {
  51321. if (!this._isStarted) {
  51322. return this;
  51323. }
  51324. for (var index = 0; index < this._animatables.length; index++) {
  51325. var animatable = this._animatables[index];
  51326. animatable.reset();
  51327. }
  51328. return this;
  51329. };
  51330. /**
  51331. * Restart animations from key 0
  51332. */
  51333. AnimationGroup.prototype.restart = function () {
  51334. if (!this._isStarted) {
  51335. return this;
  51336. }
  51337. for (var index = 0; index < this._animatables.length; index++) {
  51338. var animatable = this._animatables[index];
  51339. animatable.restart();
  51340. }
  51341. return this;
  51342. };
  51343. /**
  51344. * Stop all animations
  51345. */
  51346. AnimationGroup.prototype.stop = function () {
  51347. if (!this._isStarted) {
  51348. return this;
  51349. }
  51350. for (var index = 0; index < this._animatables.length; index++) {
  51351. var animatable = this._animatables[index];
  51352. animatable.stop();
  51353. }
  51354. this._isStarted = false;
  51355. return this;
  51356. };
  51357. /**
  51358. * Set animation weight for all animatables
  51359. * @param weight defines the weight to use
  51360. * @return the animationGroup
  51361. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51362. */
  51363. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51364. for (var index = 0; index < this._animatables.length; index++) {
  51365. var animatable = this._animatables[index];
  51366. animatable.weight = weight;
  51367. }
  51368. return this;
  51369. };
  51370. /**
  51371. * Synchronize and normalize all animatables with a source animatable
  51372. * @param root defines the root animatable to synchronize with
  51373. * @return the animationGroup
  51374. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51375. */
  51376. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51377. for (var index = 0; index < this._animatables.length; index++) {
  51378. var animatable = this._animatables[index];
  51379. animatable.syncWith(root);
  51380. }
  51381. return this;
  51382. };
  51383. /**
  51384. * Goes to a specific frame in this animation group
  51385. * @param frame the frame number to go to
  51386. * @return the animationGroup
  51387. */
  51388. AnimationGroup.prototype.goToFrame = function (frame) {
  51389. if (!this._isStarted) {
  51390. return this;
  51391. }
  51392. for (var index = 0; index < this._animatables.length; index++) {
  51393. var animatable = this._animatables[index];
  51394. animatable.goToFrame(frame);
  51395. }
  51396. return this;
  51397. };
  51398. /**
  51399. * Dispose all associated resources
  51400. */
  51401. AnimationGroup.prototype.dispose = function () {
  51402. this._targetedAnimations = [];
  51403. this._animatables = [];
  51404. var index = this._scene.animationGroups.indexOf(this);
  51405. if (index > -1) {
  51406. this._scene.animationGroups.splice(index, 1);
  51407. }
  51408. };
  51409. return AnimationGroup;
  51410. }());
  51411. BABYLON.AnimationGroup = AnimationGroup;
  51412. })(BABYLON || (BABYLON = {}));
  51413. //# sourceMappingURL=babylon.animationGroup.js.map
  51414. var BABYLON;
  51415. (function (BABYLON) {
  51416. /**
  51417. * Defines a runtime animation
  51418. */
  51419. var RuntimeAnimation = /** @class */ (function () {
  51420. /**
  51421. * Create a new RuntimeAnimation object
  51422. * @param target defines the target of the animation
  51423. * @param animation defines the source animation object
  51424. * @param scene defines the hosting scene
  51425. * @param host defines the initiating Animatable
  51426. */
  51427. function RuntimeAnimation(target, animation, scene, host) {
  51428. /**
  51429. * The current frame of the runtime animation
  51430. */
  51431. this._currentFrame = 0;
  51432. /**
  51433. * The offsets cache of the runtime animation
  51434. */
  51435. this._offsetsCache = {};
  51436. /**
  51437. * The high limits cache of the runtime animation
  51438. */
  51439. this._highLimitsCache = {};
  51440. /**
  51441. * Specifies if the runtime animation has been stopped
  51442. */
  51443. this._stopped = false;
  51444. /**
  51445. * The blending factor of the runtime animation
  51446. */
  51447. this._blendingFactor = 0;
  51448. /**
  51449. * The target path of the runtime animation
  51450. */
  51451. this._targetPath = "";
  51452. /**
  51453. * The weight of the runtime animation
  51454. */
  51455. this._weight = 1.0;
  51456. /**
  51457. * The ratio offset of the runtime animation
  51458. */
  51459. this._ratioOffset = 0;
  51460. /**
  51461. * The previous delay of the runtime animation
  51462. */
  51463. this._previousDelay = 0;
  51464. /**
  51465. * The previous ratio of the runtime animation
  51466. */
  51467. this._previousRatio = 0;
  51468. this._animation = animation;
  51469. this._target = target;
  51470. this._scene = scene;
  51471. this._host = host;
  51472. animation._runtimeAnimations.push(this);
  51473. }
  51474. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51475. /**
  51476. * Gets the current frame of the runtime animation
  51477. */
  51478. get: function () {
  51479. return this._currentFrame;
  51480. },
  51481. enumerable: true,
  51482. configurable: true
  51483. });
  51484. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51485. /**
  51486. * Gets the weight of the runtime animation
  51487. */
  51488. get: function () {
  51489. return this._weight;
  51490. },
  51491. enumerable: true,
  51492. configurable: true
  51493. });
  51494. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51495. /**
  51496. * Gets the original value of the runtime animation
  51497. */
  51498. get: function () {
  51499. return this._originalValue;
  51500. },
  51501. enumerable: true,
  51502. configurable: true
  51503. });
  51504. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51505. /**
  51506. * Gets the current value of the runtime animation
  51507. */
  51508. get: function () {
  51509. return this._currentValue;
  51510. },
  51511. enumerable: true,
  51512. configurable: true
  51513. });
  51514. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51515. /**
  51516. * Gets the target path of the runtime animation
  51517. */
  51518. get: function () {
  51519. return this._targetPath;
  51520. },
  51521. enumerable: true,
  51522. configurable: true
  51523. });
  51524. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51525. /**
  51526. * Gets the actual target of the runtime animation
  51527. */
  51528. get: function () {
  51529. return this._activeTarget;
  51530. },
  51531. enumerable: true,
  51532. configurable: true
  51533. });
  51534. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51535. /**
  51536. * Gets the animation from the runtime animation
  51537. */
  51538. get: function () {
  51539. return this._animation;
  51540. },
  51541. enumerable: true,
  51542. configurable: true
  51543. });
  51544. /**
  51545. * Resets the runtime animation to the beginning
  51546. */
  51547. RuntimeAnimation.prototype.reset = function () {
  51548. this._offsetsCache = {};
  51549. this._highLimitsCache = {};
  51550. this._currentFrame = 0;
  51551. this._blendingFactor = 0;
  51552. this._originalValue = null;
  51553. };
  51554. /**
  51555. * Specifies if the runtime animation is stopped
  51556. * @returns Boolean specifying if the runtime animation is stopped
  51557. */
  51558. RuntimeAnimation.prototype.isStopped = function () {
  51559. return this._stopped;
  51560. };
  51561. /**
  51562. * Disposes of the runtime animation
  51563. */
  51564. RuntimeAnimation.prototype.dispose = function () {
  51565. var index = this._animation.runtimeAnimations.indexOf(this);
  51566. if (index > -1) {
  51567. this._animation.runtimeAnimations.splice(index, 1);
  51568. }
  51569. };
  51570. /**
  51571. * Interpolates the animation from the current frame
  51572. * @param currentFrame The frame to interpolate the animation to
  51573. * @param repeatCount The number of times that the animation should loop
  51574. * @param loopMode The type of looping mode to use
  51575. * @param offsetValue Animation offset value
  51576. * @param highLimitValue The high limit value
  51577. * @returns The interpolated value
  51578. */
  51579. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51580. this._currentFrame = currentFrame;
  51581. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51582. this._workValue = BABYLON.Matrix.Zero();
  51583. }
  51584. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51585. };
  51586. /**
  51587. * Affect the interpolated value to the target
  51588. * @param currentValue defines the value computed by the animation
  51589. * @param weight defines the weight to apply to this value
  51590. */
  51591. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51592. if (weight === void 0) { weight = 1.0; }
  51593. if (this._target instanceof Array) {
  51594. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51595. var target = _a[_i];
  51596. this._setValue(target, currentValue, weight);
  51597. }
  51598. }
  51599. else {
  51600. this._setValue(this._target, currentValue, weight);
  51601. }
  51602. };
  51603. /**
  51604. * Sets the value of the runtime animation
  51605. * @param target The target property of the runtime animation
  51606. * @param currentValue The current value to use for the runtime animation
  51607. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51608. */
  51609. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51610. if (weight === void 0) { weight = 1.0; }
  51611. // Set value
  51612. var path;
  51613. var destination;
  51614. var targetPropertyPath = this._animation.targetPropertyPath;
  51615. if (targetPropertyPath.length > 1) {
  51616. var property = target[targetPropertyPath[0]];
  51617. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51618. property = property[targetPropertyPath[index]];
  51619. }
  51620. path = targetPropertyPath[targetPropertyPath.length - 1];
  51621. destination = property;
  51622. }
  51623. else {
  51624. path = targetPropertyPath[0];
  51625. destination = target;
  51626. }
  51627. this._targetPath = path;
  51628. this._activeTarget = destination;
  51629. this._weight = weight;
  51630. // Blending
  51631. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51632. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51633. if (enableBlending && this._blendingFactor <= 1.0) {
  51634. if (!this._originalBlendValue) {
  51635. var originalValue = destination[path];
  51636. if (originalValue.clone) {
  51637. this._originalBlendValue = originalValue.clone();
  51638. }
  51639. else {
  51640. this._originalBlendValue = originalValue;
  51641. }
  51642. }
  51643. }
  51644. if (weight !== -1.0) {
  51645. if (!this._originalValue) {
  51646. var originalValue = void 0;
  51647. if (destination.getRestPose && path === "_matrix") { // For bones
  51648. originalValue = destination.getRestPose();
  51649. }
  51650. else {
  51651. originalValue = destination[path];
  51652. }
  51653. if (originalValue.clone) {
  51654. this._originalValue = originalValue.clone();
  51655. }
  51656. else {
  51657. this._originalValue = originalValue;
  51658. }
  51659. }
  51660. }
  51661. if (enableBlending && this._blendingFactor <= 1.0) {
  51662. if (this._originalBlendValue.m) { // Matrix
  51663. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51664. if (this._currentValue) {
  51665. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51666. }
  51667. else {
  51668. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51669. }
  51670. }
  51671. else {
  51672. if (this._currentValue) {
  51673. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51674. }
  51675. else {
  51676. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51677. }
  51678. }
  51679. }
  51680. else {
  51681. var constructor = this._originalBlendValue.constructor;
  51682. if (constructor.Lerp) { // Lerp supported
  51683. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51684. }
  51685. else if (constructor.Slerp) { // Slerp supported
  51686. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51687. }
  51688. else if (this._originalBlendValue.toFixed) { // Number
  51689. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51690. }
  51691. else { // Blending not supported
  51692. this._currentValue = currentValue;
  51693. }
  51694. }
  51695. this._blendingFactor += blendingSpeed;
  51696. }
  51697. else {
  51698. this._currentValue = currentValue;
  51699. }
  51700. if (weight !== -1.0) {
  51701. this._scene._registerTargetForLateAnimationBinding(this);
  51702. }
  51703. else {
  51704. destination[path] = this._currentValue;
  51705. }
  51706. if (target.markAsDirty) {
  51707. target.markAsDirty(this._animation.targetProperty);
  51708. }
  51709. };
  51710. /**
  51711. * Gets the loop pmode of the runtime animation
  51712. * @returns Loop Mode
  51713. */
  51714. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51715. if (this._target && this._target.animationPropertiesOverride) {
  51716. return this._target.animationPropertiesOverride.loopMode;
  51717. }
  51718. return this._animation.loopMode;
  51719. };
  51720. /**
  51721. * Move the current animation to a given frame
  51722. * @param frame defines the frame to move to
  51723. */
  51724. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51725. var keys = this._animation.getKeys();
  51726. if (frame < keys[0].frame) {
  51727. frame = keys[0].frame;
  51728. }
  51729. else if (frame > keys[keys.length - 1].frame) {
  51730. frame = keys[keys.length - 1].frame;
  51731. }
  51732. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51733. this.setValue(currentValue, -1);
  51734. };
  51735. /**
  51736. * @hidden Internal use only
  51737. */
  51738. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51739. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51740. this._ratioOffset = this._previousRatio - newRatio;
  51741. };
  51742. /**
  51743. * Execute the current animation
  51744. * @param delay defines the delay to add to the current frame
  51745. * @param from defines the lower bound of the animation range
  51746. * @param to defines the upper bound of the animation range
  51747. * @param loop defines if the current animation must loop
  51748. * @param speedRatio defines the current speed ratio
  51749. * @param weight defines the weight of the animation (default is -1 so no weight)
  51750. * @returns a boolean indicating if the animation has ended
  51751. */
  51752. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51753. if (weight === void 0) { weight = -1.0; }
  51754. var targetPropertyPath = this._animation.targetPropertyPath;
  51755. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51756. this._stopped = true;
  51757. return false;
  51758. }
  51759. var returnValue = true;
  51760. var keys = this._animation.getKeys();
  51761. // Adding a start key at frame 0 if missing
  51762. if (keys[0].frame !== 0) {
  51763. var newKey = { frame: 0, value: keys[0].value };
  51764. keys.splice(0, 0, newKey);
  51765. }
  51766. // Check limits
  51767. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51768. from = keys[0].frame;
  51769. }
  51770. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51771. to = keys[keys.length - 1].frame;
  51772. }
  51773. //to and from cannot be the same key
  51774. if (from === to) {
  51775. if (from > keys[0].frame) {
  51776. from--;
  51777. }
  51778. else if (to < keys[keys.length - 1].frame) {
  51779. to++;
  51780. }
  51781. }
  51782. // Compute ratio
  51783. var range = to - from;
  51784. var offsetValue;
  51785. // ratio represents the frame delta between from and to
  51786. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51787. var highLimitValue = 0;
  51788. this._previousDelay = delay;
  51789. this._previousRatio = ratio;
  51790. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51791. returnValue = false;
  51792. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51793. }
  51794. else {
  51795. // Get max value if required
  51796. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51797. var keyOffset = to.toString() + from.toString();
  51798. if (!this._offsetsCache[keyOffset]) {
  51799. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51800. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51801. switch (this._animation.dataType) {
  51802. // Float
  51803. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51804. this._offsetsCache[keyOffset] = toValue - fromValue;
  51805. break;
  51806. // Quaternion
  51807. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51808. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51809. break;
  51810. // Vector3
  51811. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51812. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51813. // Vector2
  51814. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51815. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51816. // Size
  51817. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51818. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51819. // Color3
  51820. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51821. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51822. default:
  51823. break;
  51824. }
  51825. this._highLimitsCache[keyOffset] = toValue;
  51826. }
  51827. highLimitValue = this._highLimitsCache[keyOffset];
  51828. offsetValue = this._offsetsCache[keyOffset];
  51829. }
  51830. }
  51831. if (offsetValue === undefined) {
  51832. switch (this._animation.dataType) {
  51833. // Float
  51834. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51835. offsetValue = 0;
  51836. break;
  51837. // Quaternion
  51838. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51839. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51840. break;
  51841. // Vector3
  51842. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51843. offsetValue = BABYLON.Vector3.Zero();
  51844. break;
  51845. // Vector2
  51846. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51847. offsetValue = BABYLON.Vector2.Zero();
  51848. break;
  51849. // Size
  51850. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51851. offsetValue = BABYLON.Size.Zero();
  51852. break;
  51853. // Color3
  51854. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51855. offsetValue = BABYLON.Color3.Black();
  51856. }
  51857. }
  51858. // Compute value
  51859. var repeatCount = (ratio / range) >> 0;
  51860. var currentFrame = returnValue ? from + ratio % range : to;
  51861. // Need to normalize?
  51862. if (this._host && this._host.syncRoot) {
  51863. var syncRoot = this._host.syncRoot;
  51864. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51865. currentFrame = from + (to - from) * hostNormalizedFrame;
  51866. }
  51867. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51868. // Set value
  51869. this.setValue(currentValue, weight);
  51870. // Check events
  51871. var events = this._animation.getEvents();
  51872. for (var index = 0; index < events.length; index++) {
  51873. // Make sure current frame has passed event frame and that event frame is within the current range
  51874. // Also, handle both forward and reverse animations
  51875. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51876. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51877. var event = events[index];
  51878. if (!event.isDone) {
  51879. // If event should be done only once, remove it.
  51880. if (event.onlyOnce) {
  51881. events.splice(index, 1);
  51882. index--;
  51883. }
  51884. event.isDone = true;
  51885. event.action();
  51886. } // Don't do anything if the event has already be done.
  51887. }
  51888. else if (events[index].isDone && !events[index].onlyOnce) {
  51889. // reset event, the animation is looping
  51890. events[index].isDone = false;
  51891. }
  51892. }
  51893. if (!returnValue) {
  51894. this._stopped = true;
  51895. }
  51896. return returnValue;
  51897. };
  51898. return RuntimeAnimation;
  51899. }());
  51900. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51901. })(BABYLON || (BABYLON = {}));
  51902. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51903. var BABYLON;
  51904. (function (BABYLON) {
  51905. var Animatable = /** @class */ (function () {
  51906. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51907. if (fromFrame === void 0) { fromFrame = 0; }
  51908. if (toFrame === void 0) { toFrame = 100; }
  51909. if (loopAnimation === void 0) { loopAnimation = false; }
  51910. if (speedRatio === void 0) { speedRatio = 1.0; }
  51911. this.target = target;
  51912. this.fromFrame = fromFrame;
  51913. this.toFrame = toFrame;
  51914. this.loopAnimation = loopAnimation;
  51915. this.onAnimationEnd = onAnimationEnd;
  51916. this._localDelayOffset = null;
  51917. this._pausedDelay = null;
  51918. this._runtimeAnimations = new Array();
  51919. this._paused = false;
  51920. this._speedRatio = 1;
  51921. this._weight = -1.0;
  51922. this.animationStarted = false;
  51923. this._scene = scene;
  51924. if (animations) {
  51925. this.appendAnimations(target, animations);
  51926. }
  51927. this._speedRatio = speedRatio;
  51928. scene._activeAnimatables.push(this);
  51929. }
  51930. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51931. /**
  51932. * Gets the root Animatable used to synchronize and normalize animations
  51933. */
  51934. get: function () {
  51935. return this._syncRoot;
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51941. /**
  51942. * Gets the current frame of the first RuntimeAnimation
  51943. * Used to synchronize Animatables
  51944. */
  51945. get: function () {
  51946. if (this._runtimeAnimations.length === 0) {
  51947. return 0;
  51948. }
  51949. return this._runtimeAnimations[0].currentFrame;
  51950. },
  51951. enumerable: true,
  51952. configurable: true
  51953. });
  51954. Object.defineProperty(Animatable.prototype, "weight", {
  51955. /**
  51956. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51957. */
  51958. get: function () {
  51959. return this._weight;
  51960. },
  51961. set: function (value) {
  51962. if (value === -1) { // -1 is ok and means no weight
  51963. this._weight = -1;
  51964. return;
  51965. }
  51966. // Else weight must be in [0, 1] range
  51967. this._weight = Math.min(Math.max(value, 0), 1.0);
  51968. },
  51969. enumerable: true,
  51970. configurable: true
  51971. });
  51972. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51973. /**
  51974. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51975. */
  51976. get: function () {
  51977. return this._speedRatio;
  51978. },
  51979. set: function (value) {
  51980. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51981. var animation = this._runtimeAnimations[index];
  51982. animation._prepareForSpeedRatioChange(value);
  51983. }
  51984. this._speedRatio = value;
  51985. },
  51986. enumerable: true,
  51987. configurable: true
  51988. });
  51989. // Methods
  51990. /**
  51991. * Synchronize and normalize current Animatable with a source Animatable
  51992. * This is useful when using animation weights and when animations are not of the same length
  51993. * @param root defines the root Animatable to synchronize with
  51994. * @returns the current Animatable
  51995. */
  51996. Animatable.prototype.syncWith = function (root) {
  51997. this._syncRoot = root;
  51998. if (root) {
  51999. // Make sure this animatable will animate after the root
  52000. var index = this._scene._activeAnimatables.indexOf(this);
  52001. if (index > -1) {
  52002. this._scene._activeAnimatables.splice(index, 1);
  52003. this._scene._activeAnimatables.push(this);
  52004. }
  52005. }
  52006. return this;
  52007. };
  52008. Animatable.prototype.getAnimations = function () {
  52009. return this._runtimeAnimations;
  52010. };
  52011. Animatable.prototype.appendAnimations = function (target, animations) {
  52012. for (var index = 0; index < animations.length; index++) {
  52013. var animation = animations[index];
  52014. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52015. }
  52016. };
  52017. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52018. var runtimeAnimations = this._runtimeAnimations;
  52019. for (var index = 0; index < runtimeAnimations.length; index++) {
  52020. if (runtimeAnimations[index].animation.targetProperty === property) {
  52021. return runtimeAnimations[index].animation;
  52022. }
  52023. }
  52024. return null;
  52025. };
  52026. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52027. var runtimeAnimations = this._runtimeAnimations;
  52028. for (var index = 0; index < runtimeAnimations.length; index++) {
  52029. if (runtimeAnimations[index].animation.targetProperty === property) {
  52030. return runtimeAnimations[index];
  52031. }
  52032. }
  52033. return null;
  52034. };
  52035. Animatable.prototype.reset = function () {
  52036. var runtimeAnimations = this._runtimeAnimations;
  52037. for (var index = 0; index < runtimeAnimations.length; index++) {
  52038. runtimeAnimations[index].reset();
  52039. }
  52040. // Reset to original value
  52041. for (index = 0; index < runtimeAnimations.length; index++) {
  52042. var animation = runtimeAnimations[index];
  52043. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52044. }
  52045. this._localDelayOffset = null;
  52046. this._pausedDelay = null;
  52047. };
  52048. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52049. var runtimeAnimations = this._runtimeAnimations;
  52050. for (var index = 0; index < runtimeAnimations.length; index++) {
  52051. runtimeAnimations[index].animation.enableBlending = true;
  52052. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52053. }
  52054. };
  52055. Animatable.prototype.disableBlending = function () {
  52056. var runtimeAnimations = this._runtimeAnimations;
  52057. for (var index = 0; index < runtimeAnimations.length; index++) {
  52058. runtimeAnimations[index].animation.enableBlending = false;
  52059. }
  52060. };
  52061. Animatable.prototype.goToFrame = function (frame) {
  52062. var runtimeAnimations = this._runtimeAnimations;
  52063. if (runtimeAnimations[0]) {
  52064. var fps = runtimeAnimations[0].animation.framePerSecond;
  52065. var currentFrame = runtimeAnimations[0].currentFrame;
  52066. var adjustTime = frame - currentFrame;
  52067. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52068. if (this._localDelayOffset === null) {
  52069. this._localDelayOffset = 0;
  52070. }
  52071. this._localDelayOffset -= delay;
  52072. }
  52073. for (var index = 0; index < runtimeAnimations.length; index++) {
  52074. runtimeAnimations[index].goToFrame(frame);
  52075. }
  52076. };
  52077. Animatable.prototype.pause = function () {
  52078. if (this._paused) {
  52079. return;
  52080. }
  52081. this._paused = true;
  52082. };
  52083. Animatable.prototype.restart = function () {
  52084. this._paused = false;
  52085. };
  52086. Animatable.prototype.stop = function (animationName) {
  52087. if (animationName) {
  52088. var idx = this._scene._activeAnimatables.indexOf(this);
  52089. if (idx > -1) {
  52090. var runtimeAnimations = this._runtimeAnimations;
  52091. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52092. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52093. continue;
  52094. }
  52095. runtimeAnimations[index].dispose();
  52096. runtimeAnimations.splice(index, 1);
  52097. }
  52098. if (runtimeAnimations.length == 0) {
  52099. this._scene._activeAnimatables.splice(idx, 1);
  52100. if (this.onAnimationEnd) {
  52101. this.onAnimationEnd();
  52102. }
  52103. }
  52104. }
  52105. }
  52106. else {
  52107. var index = this._scene._activeAnimatables.indexOf(this);
  52108. if (index > -1) {
  52109. this._scene._activeAnimatables.splice(index, 1);
  52110. var runtimeAnimations = this._runtimeAnimations;
  52111. for (var index = 0; index < runtimeAnimations.length; index++) {
  52112. runtimeAnimations[index].dispose();
  52113. }
  52114. if (this.onAnimationEnd) {
  52115. this.onAnimationEnd();
  52116. }
  52117. }
  52118. }
  52119. };
  52120. Animatable.prototype._animate = function (delay) {
  52121. if (this._paused) {
  52122. this.animationStarted = false;
  52123. if (this._pausedDelay === null) {
  52124. this._pausedDelay = delay;
  52125. }
  52126. return true;
  52127. }
  52128. if (this._localDelayOffset === null) {
  52129. this._localDelayOffset = delay;
  52130. this._pausedDelay = null;
  52131. }
  52132. else if (this._pausedDelay !== null) {
  52133. this._localDelayOffset += delay - this._pausedDelay;
  52134. this._pausedDelay = null;
  52135. }
  52136. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52137. return true;
  52138. }
  52139. // Animating
  52140. var running = false;
  52141. var runtimeAnimations = this._runtimeAnimations;
  52142. var index;
  52143. for (index = 0; index < runtimeAnimations.length; index++) {
  52144. var animation = runtimeAnimations[index];
  52145. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52146. running = running || isRunning;
  52147. }
  52148. this.animationStarted = running;
  52149. if (!running) {
  52150. // Remove from active animatables
  52151. index = this._scene._activeAnimatables.indexOf(this);
  52152. this._scene._activeAnimatables.splice(index, 1);
  52153. // Dispose all runtime animations
  52154. for (index = 0; index < runtimeAnimations.length; index++) {
  52155. runtimeAnimations[index].dispose();
  52156. }
  52157. }
  52158. if (!running && this.onAnimationEnd) {
  52159. this.onAnimationEnd();
  52160. this.onAnimationEnd = null;
  52161. }
  52162. return running;
  52163. };
  52164. return Animatable;
  52165. }());
  52166. BABYLON.Animatable = Animatable;
  52167. })(BABYLON || (BABYLON = {}));
  52168. //# sourceMappingURL=babylon.animatable.js.map
  52169. var BABYLON;
  52170. (function (BABYLON) {
  52171. var EasingFunction = /** @class */ (function () {
  52172. function EasingFunction() {
  52173. // Properties
  52174. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52175. }
  52176. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52177. get: function () {
  52178. return EasingFunction._EASINGMODE_EASEIN;
  52179. },
  52180. enumerable: true,
  52181. configurable: true
  52182. });
  52183. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52184. get: function () {
  52185. return EasingFunction._EASINGMODE_EASEOUT;
  52186. },
  52187. enumerable: true,
  52188. configurable: true
  52189. });
  52190. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52191. get: function () {
  52192. return EasingFunction._EASINGMODE_EASEINOUT;
  52193. },
  52194. enumerable: true,
  52195. configurable: true
  52196. });
  52197. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52198. var n = Math.min(Math.max(easingMode, 0), 2);
  52199. this._easingMode = n;
  52200. };
  52201. EasingFunction.prototype.getEasingMode = function () {
  52202. return this._easingMode;
  52203. };
  52204. EasingFunction.prototype.easeInCore = function (gradient) {
  52205. throw new Error('You must implement this method');
  52206. };
  52207. EasingFunction.prototype.ease = function (gradient) {
  52208. switch (this._easingMode) {
  52209. case EasingFunction.EASINGMODE_EASEIN:
  52210. return this.easeInCore(gradient);
  52211. case EasingFunction.EASINGMODE_EASEOUT:
  52212. return (1 - this.easeInCore(1 - gradient));
  52213. }
  52214. if (gradient >= 0.5) {
  52215. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52216. }
  52217. return (this.easeInCore(gradient * 2) * 0.5);
  52218. };
  52219. //Statics
  52220. EasingFunction._EASINGMODE_EASEIN = 0;
  52221. EasingFunction._EASINGMODE_EASEOUT = 1;
  52222. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52223. return EasingFunction;
  52224. }());
  52225. BABYLON.EasingFunction = EasingFunction;
  52226. var CircleEase = /** @class */ (function (_super) {
  52227. __extends(CircleEase, _super);
  52228. function CircleEase() {
  52229. return _super !== null && _super.apply(this, arguments) || this;
  52230. }
  52231. CircleEase.prototype.easeInCore = function (gradient) {
  52232. gradient = Math.max(0, Math.min(1, gradient));
  52233. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52234. };
  52235. return CircleEase;
  52236. }(EasingFunction));
  52237. BABYLON.CircleEase = CircleEase;
  52238. var BackEase = /** @class */ (function (_super) {
  52239. __extends(BackEase, _super);
  52240. function BackEase(amplitude) {
  52241. if (amplitude === void 0) { amplitude = 1; }
  52242. var _this = _super.call(this) || this;
  52243. _this.amplitude = amplitude;
  52244. return _this;
  52245. }
  52246. BackEase.prototype.easeInCore = function (gradient) {
  52247. var num = Math.max(0, this.amplitude);
  52248. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52249. };
  52250. return BackEase;
  52251. }(EasingFunction));
  52252. BABYLON.BackEase = BackEase;
  52253. var BounceEase = /** @class */ (function (_super) {
  52254. __extends(BounceEase, _super);
  52255. function BounceEase(bounces, bounciness) {
  52256. if (bounces === void 0) { bounces = 3; }
  52257. if (bounciness === void 0) { bounciness = 2; }
  52258. var _this = _super.call(this) || this;
  52259. _this.bounces = bounces;
  52260. _this.bounciness = bounciness;
  52261. return _this;
  52262. }
  52263. BounceEase.prototype.easeInCore = function (gradient) {
  52264. var y = Math.max(0.0, this.bounces);
  52265. var bounciness = this.bounciness;
  52266. if (bounciness <= 1.0) {
  52267. bounciness = 1.001;
  52268. }
  52269. var num9 = Math.pow(bounciness, y);
  52270. var num5 = 1.0 - bounciness;
  52271. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52272. var num15 = gradient * num4;
  52273. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52274. var num3 = Math.floor(num65);
  52275. var num13 = num3 + 1.0;
  52276. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52277. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52278. var num7 = (num8 + num12) * 0.5;
  52279. var num6 = gradient - num7;
  52280. var num2 = num7 - num8;
  52281. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52282. };
  52283. return BounceEase;
  52284. }(EasingFunction));
  52285. BABYLON.BounceEase = BounceEase;
  52286. var CubicEase = /** @class */ (function (_super) {
  52287. __extends(CubicEase, _super);
  52288. function CubicEase() {
  52289. return _super !== null && _super.apply(this, arguments) || this;
  52290. }
  52291. CubicEase.prototype.easeInCore = function (gradient) {
  52292. return (gradient * gradient * gradient);
  52293. };
  52294. return CubicEase;
  52295. }(EasingFunction));
  52296. BABYLON.CubicEase = CubicEase;
  52297. var ElasticEase = /** @class */ (function (_super) {
  52298. __extends(ElasticEase, _super);
  52299. function ElasticEase(oscillations, springiness) {
  52300. if (oscillations === void 0) { oscillations = 3; }
  52301. if (springiness === void 0) { springiness = 3; }
  52302. var _this = _super.call(this) || this;
  52303. _this.oscillations = oscillations;
  52304. _this.springiness = springiness;
  52305. return _this;
  52306. }
  52307. ElasticEase.prototype.easeInCore = function (gradient) {
  52308. var num2;
  52309. var num3 = Math.max(0.0, this.oscillations);
  52310. var num = Math.max(0.0, this.springiness);
  52311. if (num == 0) {
  52312. num2 = gradient;
  52313. }
  52314. else {
  52315. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52316. }
  52317. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52318. };
  52319. return ElasticEase;
  52320. }(EasingFunction));
  52321. BABYLON.ElasticEase = ElasticEase;
  52322. var ExponentialEase = /** @class */ (function (_super) {
  52323. __extends(ExponentialEase, _super);
  52324. function ExponentialEase(exponent) {
  52325. if (exponent === void 0) { exponent = 2; }
  52326. var _this = _super.call(this) || this;
  52327. _this.exponent = exponent;
  52328. return _this;
  52329. }
  52330. ExponentialEase.prototype.easeInCore = function (gradient) {
  52331. if (this.exponent <= 0) {
  52332. return gradient;
  52333. }
  52334. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52335. };
  52336. return ExponentialEase;
  52337. }(EasingFunction));
  52338. BABYLON.ExponentialEase = ExponentialEase;
  52339. var PowerEase = /** @class */ (function (_super) {
  52340. __extends(PowerEase, _super);
  52341. function PowerEase(power) {
  52342. if (power === void 0) { power = 2; }
  52343. var _this = _super.call(this) || this;
  52344. _this.power = power;
  52345. return _this;
  52346. }
  52347. PowerEase.prototype.easeInCore = function (gradient) {
  52348. var y = Math.max(0.0, this.power);
  52349. return Math.pow(gradient, y);
  52350. };
  52351. return PowerEase;
  52352. }(EasingFunction));
  52353. BABYLON.PowerEase = PowerEase;
  52354. var QuadraticEase = /** @class */ (function (_super) {
  52355. __extends(QuadraticEase, _super);
  52356. function QuadraticEase() {
  52357. return _super !== null && _super.apply(this, arguments) || this;
  52358. }
  52359. QuadraticEase.prototype.easeInCore = function (gradient) {
  52360. return (gradient * gradient);
  52361. };
  52362. return QuadraticEase;
  52363. }(EasingFunction));
  52364. BABYLON.QuadraticEase = QuadraticEase;
  52365. var QuarticEase = /** @class */ (function (_super) {
  52366. __extends(QuarticEase, _super);
  52367. function QuarticEase() {
  52368. return _super !== null && _super.apply(this, arguments) || this;
  52369. }
  52370. QuarticEase.prototype.easeInCore = function (gradient) {
  52371. return (gradient * gradient * gradient * gradient);
  52372. };
  52373. return QuarticEase;
  52374. }(EasingFunction));
  52375. BABYLON.QuarticEase = QuarticEase;
  52376. var QuinticEase = /** @class */ (function (_super) {
  52377. __extends(QuinticEase, _super);
  52378. function QuinticEase() {
  52379. return _super !== null && _super.apply(this, arguments) || this;
  52380. }
  52381. QuinticEase.prototype.easeInCore = function (gradient) {
  52382. return (gradient * gradient * gradient * gradient * gradient);
  52383. };
  52384. return QuinticEase;
  52385. }(EasingFunction));
  52386. BABYLON.QuinticEase = QuinticEase;
  52387. var SineEase = /** @class */ (function (_super) {
  52388. __extends(SineEase, _super);
  52389. function SineEase() {
  52390. return _super !== null && _super.apply(this, arguments) || this;
  52391. }
  52392. SineEase.prototype.easeInCore = function (gradient) {
  52393. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52394. };
  52395. return SineEase;
  52396. }(EasingFunction));
  52397. BABYLON.SineEase = SineEase;
  52398. var BezierCurveEase = /** @class */ (function (_super) {
  52399. __extends(BezierCurveEase, _super);
  52400. function BezierCurveEase(x1, y1, x2, y2) {
  52401. if (x1 === void 0) { x1 = 0; }
  52402. if (y1 === void 0) { y1 = 0; }
  52403. if (x2 === void 0) { x2 = 1; }
  52404. if (y2 === void 0) { y2 = 1; }
  52405. var _this = _super.call(this) || this;
  52406. _this.x1 = x1;
  52407. _this.y1 = y1;
  52408. _this.x2 = x2;
  52409. _this.y2 = y2;
  52410. return _this;
  52411. }
  52412. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52413. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52414. };
  52415. return BezierCurveEase;
  52416. }(EasingFunction));
  52417. BABYLON.BezierCurveEase = BezierCurveEase;
  52418. })(BABYLON || (BABYLON = {}));
  52419. //# sourceMappingURL=babylon.easing.js.map
  52420. var BABYLON;
  52421. (function (BABYLON) {
  52422. /**
  52423. * A Condition applied to an Action
  52424. */
  52425. var Condition = /** @class */ (function () {
  52426. /**
  52427. * Creates a new Condition
  52428. * @param actionManager the manager of the action the condition is applied to
  52429. */
  52430. function Condition(actionManager) {
  52431. this._actionManager = actionManager;
  52432. }
  52433. /**
  52434. * Check if the current condition is valid
  52435. * @returns a boolean
  52436. */
  52437. Condition.prototype.isValid = function () {
  52438. return true;
  52439. };
  52440. /**
  52441. * Internal only
  52442. * @hidden
  52443. */
  52444. Condition.prototype._getProperty = function (propertyPath) {
  52445. return this._actionManager._getProperty(propertyPath);
  52446. };
  52447. /**
  52448. * Internal only
  52449. * @hidden
  52450. */
  52451. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52452. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52453. };
  52454. /**
  52455. * Serialize placeholder for child classes
  52456. * @returns the serialized object
  52457. */
  52458. Condition.prototype.serialize = function () {
  52459. };
  52460. /**
  52461. * Internal only
  52462. * @hidden
  52463. */
  52464. Condition.prototype._serialize = function (serializedCondition) {
  52465. return {
  52466. type: 2,
  52467. children: [],
  52468. name: serializedCondition.name,
  52469. properties: serializedCondition.properties
  52470. };
  52471. };
  52472. return Condition;
  52473. }());
  52474. BABYLON.Condition = Condition;
  52475. /**
  52476. * Defines specific conditional operators as extensions of Condition
  52477. */
  52478. var ValueCondition = /** @class */ (function (_super) {
  52479. __extends(ValueCondition, _super);
  52480. /**
  52481. * Creates a new ValueCondition
  52482. * @param actionManager manager for the action the condition applies to
  52483. * @param target for the action
  52484. * @param propertyPath path to specify the property of the target the conditional operator uses
  52485. * @param value the value compared by the conditional operator against the current value of the property
  52486. * @param operator the conditional operator, default ValueCondition.IsEqual
  52487. */
  52488. function ValueCondition(actionManager, target,
  52489. /** path to specify the property of the target the conditional operator uses */
  52490. propertyPath,
  52491. /** the value compared by the conditional operator against the current value of the property */
  52492. value,
  52493. /** the conditional operator, default ValueCondition.IsEqual */
  52494. operator) {
  52495. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52496. var _this = _super.call(this, actionManager) || this;
  52497. _this.propertyPath = propertyPath;
  52498. _this.value = value;
  52499. _this.operator = operator;
  52500. _this._target = target;
  52501. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52502. _this._property = _this._getProperty(_this.propertyPath);
  52503. return _this;
  52504. }
  52505. Object.defineProperty(ValueCondition, "IsEqual", {
  52506. /**
  52507. * returns the number for IsEqual
  52508. */
  52509. get: function () {
  52510. return ValueCondition._IsEqual;
  52511. },
  52512. enumerable: true,
  52513. configurable: true
  52514. });
  52515. Object.defineProperty(ValueCondition, "IsDifferent", {
  52516. /**
  52517. * Returns the number for IsDifferent
  52518. */
  52519. get: function () {
  52520. return ValueCondition._IsDifferent;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(ValueCondition, "IsGreater", {
  52526. /**
  52527. * Returns the number for IsGreater
  52528. */
  52529. get: function () {
  52530. return ValueCondition._IsGreater;
  52531. },
  52532. enumerable: true,
  52533. configurable: true
  52534. });
  52535. Object.defineProperty(ValueCondition, "IsLesser", {
  52536. /**
  52537. * Returns the number for IsLesser
  52538. */
  52539. get: function () {
  52540. return ValueCondition._IsLesser;
  52541. },
  52542. enumerable: true,
  52543. configurable: true
  52544. });
  52545. /**
  52546. * Compares the given value with the property value for the specified conditional operator
  52547. * @returns the result of the comparison
  52548. */
  52549. ValueCondition.prototype.isValid = function () {
  52550. switch (this.operator) {
  52551. case ValueCondition.IsGreater:
  52552. return this._effectiveTarget[this._property] > this.value;
  52553. case ValueCondition.IsLesser:
  52554. return this._effectiveTarget[this._property] < this.value;
  52555. case ValueCondition.IsEqual:
  52556. case ValueCondition.IsDifferent:
  52557. var check;
  52558. if (this.value.equals) {
  52559. check = this.value.equals(this._effectiveTarget[this._property]);
  52560. }
  52561. else {
  52562. check = this.value === this._effectiveTarget[this._property];
  52563. }
  52564. return this.operator === ValueCondition.IsEqual ? check : !check;
  52565. }
  52566. return false;
  52567. };
  52568. /**
  52569. * Serialize the ValueCondition into a JSON compatible object
  52570. * @returns serialization object
  52571. */
  52572. ValueCondition.prototype.serialize = function () {
  52573. return this._serialize({
  52574. name: "ValueCondition",
  52575. properties: [
  52576. BABYLON.Action._GetTargetProperty(this._target),
  52577. { name: "propertyPath", value: this.propertyPath },
  52578. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52579. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52580. ]
  52581. });
  52582. };
  52583. /**
  52584. * Gets the name of the conditional operator for the ValueCondition
  52585. * @param operator the conditional operator
  52586. * @returns the name
  52587. */
  52588. ValueCondition.GetOperatorName = function (operator) {
  52589. switch (operator) {
  52590. case ValueCondition._IsEqual: return "IsEqual";
  52591. case ValueCondition._IsDifferent: return "IsDifferent";
  52592. case ValueCondition._IsGreater: return "IsGreater";
  52593. case ValueCondition._IsLesser: return "IsLesser";
  52594. default: return "";
  52595. }
  52596. };
  52597. /**
  52598. * Internal only
  52599. * @hidden
  52600. */
  52601. ValueCondition._IsEqual = 0;
  52602. /**
  52603. * Internal only
  52604. * @hidden
  52605. */
  52606. ValueCondition._IsDifferent = 1;
  52607. /**
  52608. * Internal only
  52609. * @hidden
  52610. */
  52611. ValueCondition._IsGreater = 2;
  52612. /**
  52613. * Internal only
  52614. * @hidden
  52615. */
  52616. ValueCondition._IsLesser = 3;
  52617. return ValueCondition;
  52618. }(Condition));
  52619. BABYLON.ValueCondition = ValueCondition;
  52620. /**
  52621. * Defines a predicate condition as an extension of Condition
  52622. */
  52623. var PredicateCondition = /** @class */ (function (_super) {
  52624. __extends(PredicateCondition, _super);
  52625. /**
  52626. * Creates a new PredicateCondition
  52627. * @param actionManager manager for the action the condition applies to
  52628. * @param predicate defines the predicate function used to validate the condition
  52629. */
  52630. function PredicateCondition(actionManager,
  52631. /** defines the predicate function used to validate the condition */
  52632. predicate) {
  52633. var _this = _super.call(this, actionManager) || this;
  52634. _this.predicate = predicate;
  52635. return _this;
  52636. }
  52637. /**
  52638. * @returns the validity of the predicate condition
  52639. */
  52640. PredicateCondition.prototype.isValid = function () {
  52641. return this.predicate();
  52642. };
  52643. return PredicateCondition;
  52644. }(Condition));
  52645. BABYLON.PredicateCondition = PredicateCondition;
  52646. /**
  52647. * Defines a state condition as an extension of Condition
  52648. */
  52649. var StateCondition = /** @class */ (function (_super) {
  52650. __extends(StateCondition, _super);
  52651. /**
  52652. * Creates a new StateCondition
  52653. * @param actionManager manager for the action the condition applies to
  52654. * @param target of the condition
  52655. * @param value to compare with target state
  52656. */
  52657. function StateCondition(actionManager, target, value) {
  52658. var _this = _super.call(this, actionManager) || this;
  52659. _this.value = value;
  52660. _this._target = target;
  52661. return _this;
  52662. }
  52663. /**
  52664. * @returns the validity of the state
  52665. */
  52666. StateCondition.prototype.isValid = function () {
  52667. return this._target.state === this.value;
  52668. };
  52669. /**
  52670. * Serialize the StateCondition into a JSON compatible object
  52671. * @returns serialization object
  52672. */
  52673. StateCondition.prototype.serialize = function () {
  52674. return this._serialize({
  52675. name: "StateCondition",
  52676. properties: [
  52677. BABYLON.Action._GetTargetProperty(this._target),
  52678. { name: "value", value: this.value }
  52679. ]
  52680. });
  52681. };
  52682. return StateCondition;
  52683. }(Condition));
  52684. BABYLON.StateCondition = StateCondition;
  52685. })(BABYLON || (BABYLON = {}));
  52686. //# sourceMappingURL=babylon.condition.js.map
  52687. var BABYLON;
  52688. (function (BABYLON) {
  52689. /**
  52690. * The action to be carried out following a trigger
  52691. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52692. */
  52693. var Action = /** @class */ (function () {
  52694. /**
  52695. * Creates a new Action
  52696. * @param triggerOptions the trigger, with or without parameters, for the action
  52697. * @param condition an optional determinant of action
  52698. */
  52699. function Action(
  52700. /** the trigger, with or without parameters, for the action */
  52701. triggerOptions, condition) {
  52702. this.triggerOptions = triggerOptions;
  52703. /**
  52704. * An event triggered prior to action being executed.
  52705. */
  52706. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52707. if (triggerOptions.parameter) {
  52708. this.trigger = triggerOptions.trigger;
  52709. this._triggerParameter = triggerOptions.parameter;
  52710. }
  52711. else {
  52712. this.trigger = triggerOptions;
  52713. }
  52714. this._nextActiveAction = this;
  52715. this._condition = condition;
  52716. }
  52717. /**
  52718. * Internal only
  52719. * @hidden
  52720. */
  52721. Action.prototype._prepare = function () {
  52722. };
  52723. /**
  52724. * Gets the trigger parameters
  52725. * @returns the trigger parameters
  52726. */
  52727. Action.prototype.getTriggerParameter = function () {
  52728. return this._triggerParameter;
  52729. };
  52730. /**
  52731. * Internal only - executes current action event
  52732. * @hidden
  52733. */
  52734. Action.prototype._executeCurrent = function (evt) {
  52735. if (this._nextActiveAction._condition) {
  52736. var condition = this._nextActiveAction._condition;
  52737. var currentRenderId = this._actionManager.getScene().getRenderId();
  52738. // We cache the current evaluation for the current frame
  52739. if (condition._evaluationId === currentRenderId) {
  52740. if (!condition._currentResult) {
  52741. return;
  52742. }
  52743. }
  52744. else {
  52745. condition._evaluationId = currentRenderId;
  52746. if (!condition.isValid()) {
  52747. condition._currentResult = false;
  52748. return;
  52749. }
  52750. condition._currentResult = true;
  52751. }
  52752. }
  52753. this.onBeforeExecuteObservable.notifyObservers(this);
  52754. this._nextActiveAction.execute(evt);
  52755. this.skipToNextActiveAction();
  52756. };
  52757. /**
  52758. * Execute placeholder for child classes
  52759. * @param evt optional action event
  52760. */
  52761. Action.prototype.execute = function (evt) {
  52762. };
  52763. /**
  52764. * Skips to next active action
  52765. */
  52766. Action.prototype.skipToNextActiveAction = function () {
  52767. if (this._nextActiveAction._child) {
  52768. if (!this._nextActiveAction._child._actionManager) {
  52769. this._nextActiveAction._child._actionManager = this._actionManager;
  52770. }
  52771. this._nextActiveAction = this._nextActiveAction._child;
  52772. }
  52773. else {
  52774. this._nextActiveAction = this;
  52775. }
  52776. };
  52777. /**
  52778. * Adds action to chain of actions, may be a DoNothingAction
  52779. * @param action defines the next action to execute
  52780. * @returns The action passed in
  52781. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52782. */
  52783. Action.prototype.then = function (action) {
  52784. this._child = action;
  52785. action._actionManager = this._actionManager;
  52786. action._prepare();
  52787. return action;
  52788. };
  52789. /**
  52790. * Internal only
  52791. * @hidden
  52792. */
  52793. Action.prototype._getProperty = function (propertyPath) {
  52794. return this._actionManager._getProperty(propertyPath);
  52795. };
  52796. /**
  52797. * Internal only
  52798. * @hidden
  52799. */
  52800. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52801. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52802. };
  52803. /**
  52804. * Serialize placeholder for child classes
  52805. * @param parent of child
  52806. * @returns the serialized object
  52807. */
  52808. Action.prototype.serialize = function (parent) {
  52809. };
  52810. /**
  52811. * Internal only called by serialize
  52812. * @hidden
  52813. */
  52814. Action.prototype._serialize = function (serializedAction, parent) {
  52815. var serializationObject = {
  52816. type: 1,
  52817. children: [],
  52818. name: serializedAction.name,
  52819. properties: serializedAction.properties || []
  52820. };
  52821. // Serialize child
  52822. if (this._child) {
  52823. this._child.serialize(serializationObject);
  52824. }
  52825. // Check if "this" has a condition
  52826. if (this._condition) {
  52827. var serializedCondition = this._condition.serialize();
  52828. serializedCondition.children.push(serializationObject);
  52829. if (parent) {
  52830. parent.children.push(serializedCondition);
  52831. }
  52832. return serializedCondition;
  52833. }
  52834. if (parent) {
  52835. parent.children.push(serializationObject);
  52836. }
  52837. return serializationObject;
  52838. };
  52839. /**
  52840. * Internal only
  52841. * @hidden
  52842. */
  52843. Action._SerializeValueAsString = function (value) {
  52844. if (typeof value === "number") {
  52845. return value.toString();
  52846. }
  52847. if (typeof value === "boolean") {
  52848. return value ? "true" : "false";
  52849. }
  52850. if (value instanceof BABYLON.Vector2) {
  52851. return value.x + ", " + value.y;
  52852. }
  52853. if (value instanceof BABYLON.Vector3) {
  52854. return value.x + ", " + value.y + ", " + value.z;
  52855. }
  52856. if (value instanceof BABYLON.Color3) {
  52857. return value.r + ", " + value.g + ", " + value.b;
  52858. }
  52859. if (value instanceof BABYLON.Color4) {
  52860. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52861. }
  52862. return value; // string
  52863. };
  52864. /**
  52865. * Internal only
  52866. * @hidden
  52867. */
  52868. Action._GetTargetProperty = function (target) {
  52869. return {
  52870. name: "target",
  52871. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52872. : target instanceof BABYLON.Light ? "LightProperties"
  52873. : target instanceof BABYLON.Camera ? "CameraProperties"
  52874. : "SceneProperties",
  52875. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52876. };
  52877. };
  52878. return Action;
  52879. }());
  52880. BABYLON.Action = Action;
  52881. })(BABYLON || (BABYLON = {}));
  52882. //# sourceMappingURL=babylon.action.js.map
  52883. var BABYLON;
  52884. (function (BABYLON) {
  52885. /**
  52886. * ActionEvent is the event being sent when an action is triggered.
  52887. */
  52888. var ActionEvent = /** @class */ (function () {
  52889. /**
  52890. * Creates a new ActionEvent
  52891. * @param source The mesh or sprite that triggered the action
  52892. * @param pointerX The X mouse cursor position at the time of the event
  52893. * @param pointerY The Y mouse cursor position at the time of the event
  52894. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52895. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52896. * @param additionalData additional data for the event
  52897. */
  52898. function ActionEvent(
  52899. /** The mesh or sprite that triggered the action */
  52900. source,
  52901. /** The X mouse cursor position at the time of the event */
  52902. pointerX,
  52903. /** The Y mouse cursor position at the time of the event */
  52904. pointerY,
  52905. /** The mesh that is currently pointed at (can be null) */
  52906. meshUnderPointer,
  52907. /** the original (browser) event that triggered the ActionEvent */
  52908. sourceEvent,
  52909. /** additional data for the event */
  52910. additionalData) {
  52911. this.source = source;
  52912. this.pointerX = pointerX;
  52913. this.pointerY = pointerY;
  52914. this.meshUnderPointer = meshUnderPointer;
  52915. this.sourceEvent = sourceEvent;
  52916. this.additionalData = additionalData;
  52917. }
  52918. /**
  52919. * Helper function to auto-create an ActionEvent from a source mesh.
  52920. * @param source The source mesh that triggered the event
  52921. * @param evt The original (browser) event
  52922. * @param additionalData additional data for the event
  52923. * @returns the new ActionEvent
  52924. */
  52925. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52926. var scene = source.getScene();
  52927. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52928. };
  52929. /**
  52930. * Helper function to auto-create an ActionEvent from a source sprite
  52931. * @param source The source sprite that triggered the event
  52932. * @param scene Scene associated with the sprite
  52933. * @param evt The original (browser) event
  52934. * @param additionalData additional data for the event
  52935. * @returns the new ActionEvent
  52936. */
  52937. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52938. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52939. };
  52940. /**
  52941. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52942. * @param scene the scene where the event occurred
  52943. * @param evt The original (browser) event
  52944. * @returns the new ActionEvent
  52945. */
  52946. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52947. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52948. };
  52949. /**
  52950. * Helper function to auto-create an ActionEvent from a primitive
  52951. * @param prim defines the target primitive
  52952. * @param pointerPos defines the pointer position
  52953. * @param evt The original (browser) event
  52954. * @param additionalData additional data for the event
  52955. * @returns the new ActionEvent
  52956. */
  52957. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52958. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52959. };
  52960. return ActionEvent;
  52961. }());
  52962. BABYLON.ActionEvent = ActionEvent;
  52963. /**
  52964. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52965. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52966. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52967. */
  52968. var ActionManager = /** @class */ (function () {
  52969. /**
  52970. * Creates a new action manager
  52971. * @param scene defines the hosting scene
  52972. */
  52973. function ActionManager(scene) {
  52974. // Members
  52975. /** Gets the list of actions */
  52976. this.actions = new Array();
  52977. /** Gets the cursor to use when hovering items */
  52978. this.hoverCursor = '';
  52979. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52980. scene._actionManagers.push(this);
  52981. }
  52982. Object.defineProperty(ActionManager, "NothingTrigger", {
  52983. /**
  52984. * Nothing
  52985. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52986. */
  52987. get: function () {
  52988. return ActionManager._NothingTrigger;
  52989. },
  52990. enumerable: true,
  52991. configurable: true
  52992. });
  52993. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52994. /**
  52995. * On pick
  52996. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52997. */
  52998. get: function () {
  52999. return ActionManager._OnPickTrigger;
  53000. },
  53001. enumerable: true,
  53002. configurable: true
  53003. });
  53004. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53005. /**
  53006. * On left pick
  53007. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53008. */
  53009. get: function () {
  53010. return ActionManager._OnLeftPickTrigger;
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53016. /**
  53017. * On right pick
  53018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53019. */
  53020. get: function () {
  53021. return ActionManager._OnRightPickTrigger;
  53022. },
  53023. enumerable: true,
  53024. configurable: true
  53025. });
  53026. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53027. /**
  53028. * On center pick
  53029. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53030. */
  53031. get: function () {
  53032. return ActionManager._OnCenterPickTrigger;
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53038. /**
  53039. * On pick down
  53040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53041. */
  53042. get: function () {
  53043. return ActionManager._OnPickDownTrigger;
  53044. },
  53045. enumerable: true,
  53046. configurable: true
  53047. });
  53048. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53049. /**
  53050. * On double pick
  53051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53052. */
  53053. get: function () {
  53054. return ActionManager._OnDoublePickTrigger;
  53055. },
  53056. enumerable: true,
  53057. configurable: true
  53058. });
  53059. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53060. /**
  53061. * On pick up
  53062. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53063. */
  53064. get: function () {
  53065. return ActionManager._OnPickUpTrigger;
  53066. },
  53067. enumerable: true,
  53068. configurable: true
  53069. });
  53070. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53071. /**
  53072. * On pick out.
  53073. * This trigger will only be raised if you also declared a OnPickDown
  53074. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53075. */
  53076. get: function () {
  53077. return ActionManager._OnPickOutTrigger;
  53078. },
  53079. enumerable: true,
  53080. configurable: true
  53081. });
  53082. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53083. /**
  53084. * On long press
  53085. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53086. */
  53087. get: function () {
  53088. return ActionManager._OnLongPressTrigger;
  53089. },
  53090. enumerable: true,
  53091. configurable: true
  53092. });
  53093. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53094. /**
  53095. * On pointer over
  53096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53097. */
  53098. get: function () {
  53099. return ActionManager._OnPointerOverTrigger;
  53100. },
  53101. enumerable: true,
  53102. configurable: true
  53103. });
  53104. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53105. /**
  53106. * On pointer out
  53107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53108. */
  53109. get: function () {
  53110. return ActionManager._OnPointerOutTrigger;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53116. /**
  53117. * On every frame
  53118. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53119. */
  53120. get: function () {
  53121. return ActionManager._OnEveryFrameTrigger;
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53127. /**
  53128. * On intersection enter
  53129. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53130. */
  53131. get: function () {
  53132. return ActionManager._OnIntersectionEnterTrigger;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53138. /**
  53139. * On intersection exit
  53140. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53141. */
  53142. get: function () {
  53143. return ActionManager._OnIntersectionExitTrigger;
  53144. },
  53145. enumerable: true,
  53146. configurable: true
  53147. });
  53148. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53149. /**
  53150. * On key down
  53151. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53152. */
  53153. get: function () {
  53154. return ActionManager._OnKeyDownTrigger;
  53155. },
  53156. enumerable: true,
  53157. configurable: true
  53158. });
  53159. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53160. /**
  53161. * On key up
  53162. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53163. */
  53164. get: function () {
  53165. return ActionManager._OnKeyUpTrigger;
  53166. },
  53167. enumerable: true,
  53168. configurable: true
  53169. });
  53170. // Methods
  53171. /**
  53172. * Releases all associated resources
  53173. */
  53174. ActionManager.prototype.dispose = function () {
  53175. var index = this._scene._actionManagers.indexOf(this);
  53176. for (var i = 0; i < this.actions.length; i++) {
  53177. var action = this.actions[i];
  53178. ActionManager.Triggers[action.trigger]--;
  53179. if (ActionManager.Triggers[action.trigger] === 0) {
  53180. delete ActionManager.Triggers[action.trigger];
  53181. }
  53182. }
  53183. if (index > -1) {
  53184. this._scene._actionManagers.splice(index, 1);
  53185. }
  53186. };
  53187. /**
  53188. * Gets hosting scene
  53189. * @returns the hosting scene
  53190. */
  53191. ActionManager.prototype.getScene = function () {
  53192. return this._scene;
  53193. };
  53194. /**
  53195. * Does this action manager handles actions of any of the given triggers
  53196. * @param triggers defines the triggers to be tested
  53197. * @return a boolean indicating whether one (or more) of the triggers is handled
  53198. */
  53199. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53200. for (var index = 0; index < this.actions.length; index++) {
  53201. var action = this.actions[index];
  53202. if (triggers.indexOf(action.trigger) > -1) {
  53203. return true;
  53204. }
  53205. }
  53206. return false;
  53207. };
  53208. /**
  53209. * Does this action manager handles actions of a given trigger
  53210. * @param trigger defines the trigger to be tested
  53211. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53212. * @return whether the trigger is handled
  53213. */
  53214. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53215. for (var index = 0; index < this.actions.length; index++) {
  53216. var action = this.actions[index];
  53217. if (action.trigger === trigger) {
  53218. if (parameterPredicate) {
  53219. if (parameterPredicate(action.getTriggerParameter())) {
  53220. return true;
  53221. }
  53222. }
  53223. else {
  53224. return true;
  53225. }
  53226. }
  53227. }
  53228. return false;
  53229. };
  53230. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53231. /**
  53232. * Does this action manager has pointer triggers
  53233. */
  53234. get: function () {
  53235. for (var index = 0; index < this.actions.length; index++) {
  53236. var action = this.actions[index];
  53237. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53238. return true;
  53239. }
  53240. }
  53241. return false;
  53242. },
  53243. enumerable: true,
  53244. configurable: true
  53245. });
  53246. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53247. /**
  53248. * Does this action manager has pick triggers
  53249. */
  53250. get: function () {
  53251. for (var index = 0; index < this.actions.length; index++) {
  53252. var action = this.actions[index];
  53253. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53254. return true;
  53255. }
  53256. }
  53257. return false;
  53258. },
  53259. enumerable: true,
  53260. configurable: true
  53261. });
  53262. Object.defineProperty(ActionManager, "HasTriggers", {
  53263. /**
  53264. * Does exist one action manager with at least one trigger
  53265. **/
  53266. get: function () {
  53267. for (var t in ActionManager.Triggers) {
  53268. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53269. return true;
  53270. }
  53271. }
  53272. return false;
  53273. },
  53274. enumerable: true,
  53275. configurable: true
  53276. });
  53277. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53278. /**
  53279. * Does exist one action manager with at least one pick trigger
  53280. **/
  53281. get: function () {
  53282. for (var t in ActionManager.Triggers) {
  53283. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53284. var t_int = parseInt(t);
  53285. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53286. return true;
  53287. }
  53288. }
  53289. }
  53290. return false;
  53291. },
  53292. enumerable: true,
  53293. configurable: true
  53294. });
  53295. /**
  53296. * Does exist one action manager that handles actions of a given trigger
  53297. * @param trigger defines the trigger to be tested
  53298. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53299. **/
  53300. ActionManager.HasSpecificTrigger = function (trigger) {
  53301. for (var t in ActionManager.Triggers) {
  53302. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53303. var t_int = parseInt(t);
  53304. if (t_int === trigger) {
  53305. return true;
  53306. }
  53307. }
  53308. }
  53309. return false;
  53310. };
  53311. /**
  53312. * Registers an action to this action manager
  53313. * @param action defines the action to be registered
  53314. * @return the action amended (prepared) after registration
  53315. */
  53316. ActionManager.prototype.registerAction = function (action) {
  53317. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53318. if (this.getScene().actionManager !== this) {
  53319. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53320. return null;
  53321. }
  53322. }
  53323. this.actions.push(action);
  53324. if (ActionManager.Triggers[action.trigger]) {
  53325. ActionManager.Triggers[action.trigger]++;
  53326. }
  53327. else {
  53328. ActionManager.Triggers[action.trigger] = 1;
  53329. }
  53330. action._actionManager = this;
  53331. action._prepare();
  53332. return action;
  53333. };
  53334. /**
  53335. * Unregisters an action to this action manager
  53336. * @param action defines the action to be unregistered
  53337. * @return a boolean indicating whether the action has been unregistered
  53338. */
  53339. ActionManager.prototype.unregisterAction = function (action) {
  53340. var index = this.actions.indexOf(action);
  53341. if (index !== -1) {
  53342. this.actions.splice(index, 1);
  53343. ActionManager.Triggers[action.trigger] -= 1;
  53344. if (ActionManager.Triggers[action.trigger] === 0) {
  53345. delete ActionManager.Triggers[action.trigger];
  53346. }
  53347. delete action._actionManager;
  53348. return true;
  53349. }
  53350. return false;
  53351. };
  53352. /**
  53353. * Process a specific trigger
  53354. * @param trigger defines the trigger to process
  53355. * @param evt defines the event details to be processed
  53356. */
  53357. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53358. for (var index = 0; index < this.actions.length; index++) {
  53359. var action = this.actions[index];
  53360. if (action.trigger === trigger) {
  53361. if (evt) {
  53362. if (trigger === ActionManager.OnKeyUpTrigger
  53363. || trigger === ActionManager.OnKeyDownTrigger) {
  53364. var parameter = action.getTriggerParameter();
  53365. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53366. if (!parameter.toLowerCase) {
  53367. continue;
  53368. }
  53369. var lowerCase = parameter.toLowerCase();
  53370. if (lowerCase !== evt.sourceEvent.key) {
  53371. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53372. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53373. if (actualkey !== lowerCase) {
  53374. continue;
  53375. }
  53376. }
  53377. }
  53378. }
  53379. }
  53380. action._executeCurrent(evt);
  53381. }
  53382. }
  53383. };
  53384. /** @hidden */
  53385. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53386. var properties = propertyPath.split(".");
  53387. for (var index = 0; index < properties.length - 1; index++) {
  53388. target = target[properties[index]];
  53389. }
  53390. return target;
  53391. };
  53392. /** @hidden */
  53393. ActionManager.prototype._getProperty = function (propertyPath) {
  53394. var properties = propertyPath.split(".");
  53395. return properties[properties.length - 1];
  53396. };
  53397. /**
  53398. * Serialize this manager to a JSON object
  53399. * @param name defines the property name to store this manager
  53400. * @returns a JSON representation of this manager
  53401. */
  53402. ActionManager.prototype.serialize = function (name) {
  53403. var root = {
  53404. children: new Array(),
  53405. name: name,
  53406. type: 3,
  53407. properties: new Array() // Empty for root but required
  53408. };
  53409. for (var i = 0; i < this.actions.length; i++) {
  53410. var triggerObject = {
  53411. type: 0,
  53412. children: new Array(),
  53413. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53414. properties: new Array()
  53415. };
  53416. var triggerOptions = this.actions[i].triggerOptions;
  53417. if (triggerOptions && typeof triggerOptions !== "number") {
  53418. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53419. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53420. }
  53421. else {
  53422. var parameter = {};
  53423. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53424. if (triggerOptions.parameter.mesh) {
  53425. parameter._meshId = triggerOptions.parameter.mesh.id;
  53426. }
  53427. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53428. }
  53429. }
  53430. // Serialize child action, recursively
  53431. this.actions[i].serialize(triggerObject);
  53432. // Add serialized trigger
  53433. root.children.push(triggerObject);
  53434. }
  53435. return root;
  53436. };
  53437. /**
  53438. * Creates a new ActionManager from a JSON data
  53439. * @param parsedActions defines the JSON data to read from
  53440. * @param object defines the hosting mesh
  53441. * @param scene defines the hosting scene
  53442. */
  53443. ActionManager.Parse = function (parsedActions, object, scene) {
  53444. var actionManager = new ActionManager(scene);
  53445. if (object === null)
  53446. scene.actionManager = actionManager;
  53447. else
  53448. object.actionManager = actionManager;
  53449. // instanciate a new object
  53450. var instanciate = function (name, params) {
  53451. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53452. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53453. newInstance.constructor.apply(newInstance, params);
  53454. return newInstance;
  53455. };
  53456. var parseParameter = function (name, value, target, propertyPath) {
  53457. if (propertyPath === null) {
  53458. // String, boolean or float
  53459. var floatValue = parseFloat(value);
  53460. if (value === "true" || value === "false")
  53461. return value === "true";
  53462. else
  53463. return isNaN(floatValue) ? value : floatValue;
  53464. }
  53465. var effectiveTarget = propertyPath.split(".");
  53466. var values = value.split(",");
  53467. // Get effective Target
  53468. for (var i = 0; i < effectiveTarget.length; i++) {
  53469. target = target[effectiveTarget[i]];
  53470. }
  53471. // Return appropriate value with its type
  53472. if (typeof (target) === "boolean")
  53473. return values[0] === "true";
  53474. if (typeof (target) === "string")
  53475. return values[0];
  53476. // Parameters with multiple values such as Vector3 etc.
  53477. var split = new Array();
  53478. for (var i = 0; i < values.length; i++)
  53479. split.push(parseFloat(values[i]));
  53480. if (target instanceof BABYLON.Vector3)
  53481. return BABYLON.Vector3.FromArray(split);
  53482. if (target instanceof BABYLON.Vector4)
  53483. return BABYLON.Vector4.FromArray(split);
  53484. if (target instanceof BABYLON.Color3)
  53485. return BABYLON.Color3.FromArray(split);
  53486. if (target instanceof BABYLON.Color4)
  53487. return BABYLON.Color4.FromArray(split);
  53488. return parseFloat(values[0]);
  53489. };
  53490. // traverse graph per trigger
  53491. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53492. if (combineArray === void 0) { combineArray = null; }
  53493. if (parsedAction.detached)
  53494. return;
  53495. var parameters = new Array();
  53496. var target = null;
  53497. var propertyPath = null;
  53498. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53499. // Parameters
  53500. if (parsedAction.type === 2)
  53501. parameters.push(actionManager);
  53502. else
  53503. parameters.push(trigger);
  53504. if (combine) {
  53505. var actions = new Array();
  53506. for (var j = 0; j < parsedAction.combine.length; j++) {
  53507. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53508. }
  53509. parameters.push(actions);
  53510. }
  53511. else {
  53512. for (var i = 0; i < parsedAction.properties.length; i++) {
  53513. var value = parsedAction.properties[i].value;
  53514. var name = parsedAction.properties[i].name;
  53515. var targetType = parsedAction.properties[i].targetType;
  53516. if (name === "target")
  53517. if (targetType !== null && targetType === "SceneProperties")
  53518. value = target = scene;
  53519. else
  53520. value = target = scene.getNodeByName(value);
  53521. else if (name === "parent")
  53522. value = scene.getNodeByName(value);
  53523. else if (name === "sound")
  53524. value = scene.getSoundByName(value);
  53525. else if (name !== "propertyPath") {
  53526. if (parsedAction.type === 2 && name === "operator")
  53527. value = BABYLON.ValueCondition[value];
  53528. else
  53529. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53530. }
  53531. else {
  53532. propertyPath = value;
  53533. }
  53534. parameters.push(value);
  53535. }
  53536. }
  53537. if (combineArray === null) {
  53538. parameters.push(condition);
  53539. }
  53540. else {
  53541. parameters.push(null);
  53542. }
  53543. // If interpolate value action
  53544. if (parsedAction.name === "InterpolateValueAction") {
  53545. var param = parameters[parameters.length - 2];
  53546. parameters[parameters.length - 1] = param;
  53547. parameters[parameters.length - 2] = condition;
  53548. }
  53549. // Action or condition(s) and not CombineAction
  53550. var newAction = instanciate(parsedAction.name, parameters);
  53551. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53552. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53553. if (action)
  53554. action.then(nothing);
  53555. else
  53556. actionManager.registerAction(nothing);
  53557. action = nothing;
  53558. }
  53559. if (combineArray === null) {
  53560. if (newAction instanceof BABYLON.Condition) {
  53561. condition = newAction;
  53562. newAction = action;
  53563. }
  53564. else {
  53565. condition = null;
  53566. if (action)
  53567. action.then(newAction);
  53568. else
  53569. actionManager.registerAction(newAction);
  53570. }
  53571. }
  53572. else {
  53573. combineArray.push(newAction);
  53574. }
  53575. for (var i = 0; i < parsedAction.children.length; i++)
  53576. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53577. };
  53578. // triggers
  53579. for (var i = 0; i < parsedActions.children.length; i++) {
  53580. var triggerParams;
  53581. var trigger = parsedActions.children[i];
  53582. if (trigger.properties.length > 0) {
  53583. var param = trigger.properties[0].value;
  53584. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53585. if (value._meshId) {
  53586. value.mesh = scene.getMeshByID(value._meshId);
  53587. }
  53588. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53589. }
  53590. else
  53591. triggerParams = ActionManager[trigger.name];
  53592. for (var j = 0; j < trigger.children.length; j++) {
  53593. if (!trigger.detached)
  53594. traverse(trigger.children[j], triggerParams, null, null);
  53595. }
  53596. }
  53597. };
  53598. /**
  53599. * Get a trigger name by index
  53600. * @param trigger defines the trigger index
  53601. * @returns a trigger name
  53602. */
  53603. ActionManager.GetTriggerName = function (trigger) {
  53604. switch (trigger) {
  53605. case 0: return "NothingTrigger";
  53606. case 1: return "OnPickTrigger";
  53607. case 2: return "OnLeftPickTrigger";
  53608. case 3: return "OnRightPickTrigger";
  53609. case 4: return "OnCenterPickTrigger";
  53610. case 5: return "OnPickDownTrigger";
  53611. case 6: return "OnPickUpTrigger";
  53612. case 7: return "OnLongPressTrigger";
  53613. case 8: return "OnPointerOverTrigger";
  53614. case 9: return "OnPointerOutTrigger";
  53615. case 10: return "OnEveryFrameTrigger";
  53616. case 11: return "OnIntersectionEnterTrigger";
  53617. case 12: return "OnIntersectionExitTrigger";
  53618. case 13: return "OnKeyDownTrigger";
  53619. case 14: return "OnKeyUpTrigger";
  53620. case 15: return "OnPickOutTrigger";
  53621. default: return "";
  53622. }
  53623. };
  53624. // Statics
  53625. ActionManager._NothingTrigger = 0;
  53626. ActionManager._OnPickTrigger = 1;
  53627. ActionManager._OnLeftPickTrigger = 2;
  53628. ActionManager._OnRightPickTrigger = 3;
  53629. ActionManager._OnCenterPickTrigger = 4;
  53630. ActionManager._OnPickDownTrigger = 5;
  53631. ActionManager._OnDoublePickTrigger = 6;
  53632. ActionManager._OnPickUpTrigger = 7;
  53633. ActionManager._OnLongPressTrigger = 8;
  53634. ActionManager._OnPointerOverTrigger = 9;
  53635. ActionManager._OnPointerOutTrigger = 10;
  53636. ActionManager._OnEveryFrameTrigger = 11;
  53637. ActionManager._OnIntersectionEnterTrigger = 12;
  53638. ActionManager._OnIntersectionExitTrigger = 13;
  53639. ActionManager._OnKeyDownTrigger = 14;
  53640. ActionManager._OnKeyUpTrigger = 15;
  53641. ActionManager._OnPickOutTrigger = 16;
  53642. /** Gets the list of active triggers */
  53643. ActionManager.Triggers = {};
  53644. return ActionManager;
  53645. }());
  53646. BABYLON.ActionManager = ActionManager;
  53647. })(BABYLON || (BABYLON = {}));
  53648. //# sourceMappingURL=babylon.actionManager.js.map
  53649. var BABYLON;
  53650. (function (BABYLON) {
  53651. var InterpolateValueAction = /** @class */ (function (_super) {
  53652. __extends(InterpolateValueAction, _super);
  53653. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53654. if (duration === void 0) { duration = 1000; }
  53655. var _this = _super.call(this, triggerOptions, condition) || this;
  53656. _this.propertyPath = propertyPath;
  53657. _this.value = value;
  53658. _this.duration = duration;
  53659. _this.stopOtherAnimations = stopOtherAnimations;
  53660. _this.onInterpolationDone = onInterpolationDone;
  53661. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53662. _this._target = _this._effectiveTarget = target;
  53663. return _this;
  53664. }
  53665. InterpolateValueAction.prototype._prepare = function () {
  53666. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53667. this._property = this._getProperty(this.propertyPath);
  53668. };
  53669. InterpolateValueAction.prototype.execute = function () {
  53670. var _this = this;
  53671. var scene = this._actionManager.getScene();
  53672. var keys = [
  53673. {
  53674. frame: 0,
  53675. value: this._effectiveTarget[this._property]
  53676. }, {
  53677. frame: 100,
  53678. value: this.value
  53679. }
  53680. ];
  53681. var dataType;
  53682. if (typeof this.value === "number") {
  53683. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53684. }
  53685. else if (this.value instanceof BABYLON.Color3) {
  53686. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53687. }
  53688. else if (this.value instanceof BABYLON.Vector3) {
  53689. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53690. }
  53691. else if (this.value instanceof BABYLON.Matrix) {
  53692. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53693. }
  53694. else if (this.value instanceof BABYLON.Quaternion) {
  53695. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53696. }
  53697. else {
  53698. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53699. return;
  53700. }
  53701. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53702. animation.setKeys(keys);
  53703. if (this.stopOtherAnimations) {
  53704. scene.stopAnimation(this._effectiveTarget);
  53705. }
  53706. var wrapper = function () {
  53707. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53708. if (_this.onInterpolationDone) {
  53709. _this.onInterpolationDone();
  53710. }
  53711. };
  53712. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53713. };
  53714. InterpolateValueAction.prototype.serialize = function (parent) {
  53715. return _super.prototype._serialize.call(this, {
  53716. name: "InterpolateValueAction",
  53717. properties: [
  53718. BABYLON.Action._GetTargetProperty(this._target),
  53719. { name: "propertyPath", value: this.propertyPath },
  53720. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53721. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53722. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53723. ]
  53724. }, parent);
  53725. };
  53726. return InterpolateValueAction;
  53727. }(BABYLON.Action));
  53728. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53729. })(BABYLON || (BABYLON = {}));
  53730. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53731. var BABYLON;
  53732. (function (BABYLON) {
  53733. var SwitchBooleanAction = /** @class */ (function (_super) {
  53734. __extends(SwitchBooleanAction, _super);
  53735. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53736. var _this = _super.call(this, triggerOptions, condition) || this;
  53737. _this.propertyPath = propertyPath;
  53738. _this._target = _this._effectiveTarget = target;
  53739. return _this;
  53740. }
  53741. SwitchBooleanAction.prototype._prepare = function () {
  53742. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53743. this._property = this._getProperty(this.propertyPath);
  53744. };
  53745. SwitchBooleanAction.prototype.execute = function () {
  53746. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53747. };
  53748. SwitchBooleanAction.prototype.serialize = function (parent) {
  53749. return _super.prototype._serialize.call(this, {
  53750. name: "SwitchBooleanAction",
  53751. properties: [
  53752. BABYLON.Action._GetTargetProperty(this._target),
  53753. { name: "propertyPath", value: this.propertyPath }
  53754. ]
  53755. }, parent);
  53756. };
  53757. return SwitchBooleanAction;
  53758. }(BABYLON.Action));
  53759. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53760. var SetStateAction = /** @class */ (function (_super) {
  53761. __extends(SetStateAction, _super);
  53762. function SetStateAction(triggerOptions, target, value, condition) {
  53763. var _this = _super.call(this, triggerOptions, condition) || this;
  53764. _this.value = value;
  53765. _this._target = target;
  53766. return _this;
  53767. }
  53768. SetStateAction.prototype.execute = function () {
  53769. this._target.state = this.value;
  53770. };
  53771. SetStateAction.prototype.serialize = function (parent) {
  53772. return _super.prototype._serialize.call(this, {
  53773. name: "SetStateAction",
  53774. properties: [
  53775. BABYLON.Action._GetTargetProperty(this._target),
  53776. { name: "value", value: this.value }
  53777. ]
  53778. }, parent);
  53779. };
  53780. return SetStateAction;
  53781. }(BABYLON.Action));
  53782. BABYLON.SetStateAction = SetStateAction;
  53783. var SetValueAction = /** @class */ (function (_super) {
  53784. __extends(SetValueAction, _super);
  53785. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53786. var _this = _super.call(this, triggerOptions, condition) || this;
  53787. _this.propertyPath = propertyPath;
  53788. _this.value = value;
  53789. _this._target = _this._effectiveTarget = target;
  53790. return _this;
  53791. }
  53792. SetValueAction.prototype._prepare = function () {
  53793. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53794. this._property = this._getProperty(this.propertyPath);
  53795. };
  53796. SetValueAction.prototype.execute = function () {
  53797. this._effectiveTarget[this._property] = this.value;
  53798. if (this._target.markAsDirty) {
  53799. this._target.markAsDirty(this._property);
  53800. }
  53801. };
  53802. SetValueAction.prototype.serialize = function (parent) {
  53803. return _super.prototype._serialize.call(this, {
  53804. name: "SetValueAction",
  53805. properties: [
  53806. BABYLON.Action._GetTargetProperty(this._target),
  53807. { name: "propertyPath", value: this.propertyPath },
  53808. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53809. ]
  53810. }, parent);
  53811. };
  53812. return SetValueAction;
  53813. }(BABYLON.Action));
  53814. BABYLON.SetValueAction = SetValueAction;
  53815. var IncrementValueAction = /** @class */ (function (_super) {
  53816. __extends(IncrementValueAction, _super);
  53817. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53818. var _this = _super.call(this, triggerOptions, condition) || this;
  53819. _this.propertyPath = propertyPath;
  53820. _this.value = value;
  53821. _this._target = _this._effectiveTarget = target;
  53822. return _this;
  53823. }
  53824. IncrementValueAction.prototype._prepare = function () {
  53825. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53826. this._property = this._getProperty(this.propertyPath);
  53827. if (typeof this._effectiveTarget[this._property] !== "number") {
  53828. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53829. }
  53830. };
  53831. IncrementValueAction.prototype.execute = function () {
  53832. this._effectiveTarget[this._property] += this.value;
  53833. if (this._target.markAsDirty) {
  53834. this._target.markAsDirty(this._property);
  53835. }
  53836. };
  53837. IncrementValueAction.prototype.serialize = function (parent) {
  53838. return _super.prototype._serialize.call(this, {
  53839. name: "IncrementValueAction",
  53840. properties: [
  53841. BABYLON.Action._GetTargetProperty(this._target),
  53842. { name: "propertyPath", value: this.propertyPath },
  53843. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53844. ]
  53845. }, parent);
  53846. };
  53847. return IncrementValueAction;
  53848. }(BABYLON.Action));
  53849. BABYLON.IncrementValueAction = IncrementValueAction;
  53850. var PlayAnimationAction = /** @class */ (function (_super) {
  53851. __extends(PlayAnimationAction, _super);
  53852. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53853. var _this = _super.call(this, triggerOptions, condition) || this;
  53854. _this.from = from;
  53855. _this.to = to;
  53856. _this.loop = loop;
  53857. _this._target = target;
  53858. return _this;
  53859. }
  53860. PlayAnimationAction.prototype._prepare = function () {
  53861. };
  53862. PlayAnimationAction.prototype.execute = function () {
  53863. var scene = this._actionManager.getScene();
  53864. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53865. };
  53866. PlayAnimationAction.prototype.serialize = function (parent) {
  53867. return _super.prototype._serialize.call(this, {
  53868. name: "PlayAnimationAction",
  53869. properties: [
  53870. BABYLON.Action._GetTargetProperty(this._target),
  53871. { name: "from", value: String(this.from) },
  53872. { name: "to", value: String(this.to) },
  53873. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53874. ]
  53875. }, parent);
  53876. };
  53877. return PlayAnimationAction;
  53878. }(BABYLON.Action));
  53879. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53880. var StopAnimationAction = /** @class */ (function (_super) {
  53881. __extends(StopAnimationAction, _super);
  53882. function StopAnimationAction(triggerOptions, target, condition) {
  53883. var _this = _super.call(this, triggerOptions, condition) || this;
  53884. _this._target = target;
  53885. return _this;
  53886. }
  53887. StopAnimationAction.prototype._prepare = function () {
  53888. };
  53889. StopAnimationAction.prototype.execute = function () {
  53890. var scene = this._actionManager.getScene();
  53891. scene.stopAnimation(this._target);
  53892. };
  53893. StopAnimationAction.prototype.serialize = function (parent) {
  53894. return _super.prototype._serialize.call(this, {
  53895. name: "StopAnimationAction",
  53896. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53897. }, parent);
  53898. };
  53899. return StopAnimationAction;
  53900. }(BABYLON.Action));
  53901. BABYLON.StopAnimationAction = StopAnimationAction;
  53902. var DoNothingAction = /** @class */ (function (_super) {
  53903. __extends(DoNothingAction, _super);
  53904. function DoNothingAction(triggerOptions, condition) {
  53905. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53906. return _super.call(this, triggerOptions, condition) || this;
  53907. }
  53908. DoNothingAction.prototype.execute = function () {
  53909. };
  53910. DoNothingAction.prototype.serialize = function (parent) {
  53911. return _super.prototype._serialize.call(this, {
  53912. name: "DoNothingAction",
  53913. properties: []
  53914. }, parent);
  53915. };
  53916. return DoNothingAction;
  53917. }(BABYLON.Action));
  53918. BABYLON.DoNothingAction = DoNothingAction;
  53919. var CombineAction = /** @class */ (function (_super) {
  53920. __extends(CombineAction, _super);
  53921. function CombineAction(triggerOptions, children, condition) {
  53922. var _this = _super.call(this, triggerOptions, condition) || this;
  53923. _this.children = children;
  53924. return _this;
  53925. }
  53926. CombineAction.prototype._prepare = function () {
  53927. for (var index = 0; index < this.children.length; index++) {
  53928. this.children[index]._actionManager = this._actionManager;
  53929. this.children[index]._prepare();
  53930. }
  53931. };
  53932. CombineAction.prototype.execute = function (evt) {
  53933. for (var index = 0; index < this.children.length; index++) {
  53934. this.children[index].execute(evt);
  53935. }
  53936. };
  53937. CombineAction.prototype.serialize = function (parent) {
  53938. var serializationObject = _super.prototype._serialize.call(this, {
  53939. name: "CombineAction",
  53940. properties: [],
  53941. combine: []
  53942. }, parent);
  53943. for (var i = 0; i < this.children.length; i++) {
  53944. serializationObject.combine.push(this.children[i].serialize(null));
  53945. }
  53946. return serializationObject;
  53947. };
  53948. return CombineAction;
  53949. }(BABYLON.Action));
  53950. BABYLON.CombineAction = CombineAction;
  53951. var ExecuteCodeAction = /** @class */ (function (_super) {
  53952. __extends(ExecuteCodeAction, _super);
  53953. function ExecuteCodeAction(triggerOptions, func, condition) {
  53954. var _this = _super.call(this, triggerOptions, condition) || this;
  53955. _this.func = func;
  53956. return _this;
  53957. }
  53958. ExecuteCodeAction.prototype.execute = function (evt) {
  53959. this.func(evt);
  53960. };
  53961. return ExecuteCodeAction;
  53962. }(BABYLON.Action));
  53963. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53964. var SetParentAction = /** @class */ (function (_super) {
  53965. __extends(SetParentAction, _super);
  53966. function SetParentAction(triggerOptions, target, parent, condition) {
  53967. var _this = _super.call(this, triggerOptions, condition) || this;
  53968. _this._target = target;
  53969. _this._parent = parent;
  53970. return _this;
  53971. }
  53972. SetParentAction.prototype._prepare = function () {
  53973. };
  53974. SetParentAction.prototype.execute = function () {
  53975. if (this._target.parent === this._parent) {
  53976. return;
  53977. }
  53978. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53979. invertParentWorldMatrix.invert();
  53980. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53981. this._target.parent = this._parent;
  53982. };
  53983. SetParentAction.prototype.serialize = function (parent) {
  53984. return _super.prototype._serialize.call(this, {
  53985. name: "SetParentAction",
  53986. properties: [
  53987. BABYLON.Action._GetTargetProperty(this._target),
  53988. BABYLON.Action._GetTargetProperty(this._parent),
  53989. ]
  53990. }, parent);
  53991. };
  53992. return SetParentAction;
  53993. }(BABYLON.Action));
  53994. BABYLON.SetParentAction = SetParentAction;
  53995. var PlaySoundAction = /** @class */ (function (_super) {
  53996. __extends(PlaySoundAction, _super);
  53997. function PlaySoundAction(triggerOptions, sound, condition) {
  53998. var _this = _super.call(this, triggerOptions, condition) || this;
  53999. _this._sound = sound;
  54000. return _this;
  54001. }
  54002. PlaySoundAction.prototype._prepare = function () {
  54003. };
  54004. PlaySoundAction.prototype.execute = function () {
  54005. if (this._sound !== undefined)
  54006. this._sound.play();
  54007. };
  54008. PlaySoundAction.prototype.serialize = function (parent) {
  54009. return _super.prototype._serialize.call(this, {
  54010. name: "PlaySoundAction",
  54011. properties: [{ name: "sound", value: this._sound.name }]
  54012. }, parent);
  54013. };
  54014. return PlaySoundAction;
  54015. }(BABYLON.Action));
  54016. BABYLON.PlaySoundAction = PlaySoundAction;
  54017. var StopSoundAction = /** @class */ (function (_super) {
  54018. __extends(StopSoundAction, _super);
  54019. function StopSoundAction(triggerOptions, sound, condition) {
  54020. var _this = _super.call(this, triggerOptions, condition) || this;
  54021. _this._sound = sound;
  54022. return _this;
  54023. }
  54024. StopSoundAction.prototype._prepare = function () {
  54025. };
  54026. StopSoundAction.prototype.execute = function () {
  54027. if (this._sound !== undefined)
  54028. this._sound.stop();
  54029. };
  54030. StopSoundAction.prototype.serialize = function (parent) {
  54031. return _super.prototype._serialize.call(this, {
  54032. name: "StopSoundAction",
  54033. properties: [{ name: "sound", value: this._sound.name }]
  54034. }, parent);
  54035. };
  54036. return StopSoundAction;
  54037. }(BABYLON.Action));
  54038. BABYLON.StopSoundAction = StopSoundAction;
  54039. })(BABYLON || (BABYLON = {}));
  54040. //# sourceMappingURL=babylon.directActions.js.map
  54041. var BABYLON;
  54042. (function (BABYLON) {
  54043. var SpriteManager = /** @class */ (function () {
  54044. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54045. if (epsilon === void 0) { epsilon = 0.01; }
  54046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54047. this.name = name;
  54048. this.sprites = new Array();
  54049. this.renderingGroupId = 0;
  54050. this.layerMask = 0x0FFFFFFF;
  54051. this.fogEnabled = true;
  54052. this.isPickable = false;
  54053. /**
  54054. * An event triggered when the manager is disposed.
  54055. */
  54056. this.onDisposeObservable = new BABYLON.Observable();
  54057. this._vertexBuffers = {};
  54058. this._capacity = capacity;
  54059. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54060. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54061. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54062. if (cellSize.width && cellSize.height) {
  54063. this.cellWidth = cellSize.width;
  54064. this.cellHeight = cellSize.height;
  54065. }
  54066. else if (cellSize !== undefined) {
  54067. this.cellWidth = cellSize;
  54068. this.cellHeight = cellSize;
  54069. }
  54070. else {
  54071. return;
  54072. }
  54073. this._epsilon = epsilon;
  54074. this._scene = scene;
  54075. this._scene.spriteManagers.push(this);
  54076. var indices = [];
  54077. var index = 0;
  54078. for (var count = 0; count < capacity; count++) {
  54079. indices.push(index);
  54080. indices.push(index + 1);
  54081. indices.push(index + 2);
  54082. indices.push(index);
  54083. indices.push(index + 2);
  54084. indices.push(index + 3);
  54085. index += 4;
  54086. }
  54087. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54088. // VBO
  54089. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54090. this._vertexData = new Float32Array(capacity * 16 * 4);
  54091. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54092. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54093. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54094. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54095. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54096. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54097. this._vertexBuffers["options"] = options;
  54098. this._vertexBuffers["cellInfo"] = cellInfo;
  54099. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54100. // Effects
  54101. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54102. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54103. }
  54104. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54105. set: function (callback) {
  54106. if (this._onDisposeObserver) {
  54107. this.onDisposeObservable.remove(this._onDisposeObserver);
  54108. }
  54109. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54110. },
  54111. enumerable: true,
  54112. configurable: true
  54113. });
  54114. Object.defineProperty(SpriteManager.prototype, "texture", {
  54115. get: function () {
  54116. return this._spriteTexture;
  54117. },
  54118. set: function (value) {
  54119. this._spriteTexture = value;
  54120. },
  54121. enumerable: true,
  54122. configurable: true
  54123. });
  54124. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54125. var arrayOffset = index * 16;
  54126. if (offsetX === 0)
  54127. offsetX = this._epsilon;
  54128. else if (offsetX === 1)
  54129. offsetX = 1 - this._epsilon;
  54130. if (offsetY === 0)
  54131. offsetY = this._epsilon;
  54132. else if (offsetY === 1)
  54133. offsetY = 1 - this._epsilon;
  54134. this._vertexData[arrayOffset] = sprite.position.x;
  54135. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54136. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54137. this._vertexData[arrayOffset + 3] = sprite.angle;
  54138. this._vertexData[arrayOffset + 4] = sprite.width;
  54139. this._vertexData[arrayOffset + 5] = sprite.height;
  54140. this._vertexData[arrayOffset + 6] = offsetX;
  54141. this._vertexData[arrayOffset + 7] = offsetY;
  54142. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54143. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54144. var offset = (sprite.cellIndex / rowSize) >> 0;
  54145. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54146. this._vertexData[arrayOffset + 11] = offset;
  54147. // Color
  54148. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54149. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54150. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54151. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54152. };
  54153. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54154. var count = Math.min(this._capacity, this.sprites.length);
  54155. var min = BABYLON.Vector3.Zero();
  54156. var max = BABYLON.Vector3.Zero();
  54157. var distance = Number.MAX_VALUE;
  54158. var currentSprite = null;
  54159. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54160. var cameraView = camera.getViewMatrix();
  54161. for (var index = 0; index < count; index++) {
  54162. var sprite = this.sprites[index];
  54163. if (!sprite) {
  54164. continue;
  54165. }
  54166. if (predicate) {
  54167. if (!predicate(sprite)) {
  54168. continue;
  54169. }
  54170. }
  54171. else if (!sprite.isPickable) {
  54172. continue;
  54173. }
  54174. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54175. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54176. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54177. if (ray.intersectsBoxMinMax(min, max)) {
  54178. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54179. if (distance > currentDistance) {
  54180. distance = currentDistance;
  54181. currentSprite = sprite;
  54182. if (fastCheck) {
  54183. break;
  54184. }
  54185. }
  54186. }
  54187. }
  54188. if (currentSprite) {
  54189. var result = new BABYLON.PickingInfo();
  54190. result.hit = true;
  54191. result.pickedSprite = currentSprite;
  54192. result.distance = distance;
  54193. return result;
  54194. }
  54195. return null;
  54196. };
  54197. SpriteManager.prototype.render = function () {
  54198. // Check
  54199. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54200. return;
  54201. var engine = this._scene.getEngine();
  54202. var baseSize = this._spriteTexture.getBaseSize();
  54203. // Sprites
  54204. var deltaTime = engine.getDeltaTime();
  54205. var max = Math.min(this._capacity, this.sprites.length);
  54206. var rowSize = baseSize.width / this.cellWidth;
  54207. var offset = 0;
  54208. for (var index = 0; index < max; index++) {
  54209. var sprite = this.sprites[index];
  54210. if (!sprite) {
  54211. continue;
  54212. }
  54213. sprite._animate(deltaTime);
  54214. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54215. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54216. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54217. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54218. }
  54219. this._buffer.update(this._vertexData);
  54220. // Render
  54221. var effect = this._effectBase;
  54222. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54223. effect = this._effectFog;
  54224. }
  54225. engine.enableEffect(effect);
  54226. var viewMatrix = this._scene.getViewMatrix();
  54227. effect.setTexture("diffuseSampler", this._spriteTexture);
  54228. effect.setMatrix("view", viewMatrix);
  54229. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54230. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54231. // Fog
  54232. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54233. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54234. effect.setColor3("vFogColor", this._scene.fogColor);
  54235. }
  54236. // VBOs
  54237. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54238. // Draw order
  54239. engine.setDepthFunctionToLessOrEqual();
  54240. effect.setBool("alphaTest", true);
  54241. engine.setColorWrite(false);
  54242. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54243. engine.setColorWrite(true);
  54244. effect.setBool("alphaTest", false);
  54245. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54246. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54247. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54248. };
  54249. SpriteManager.prototype.dispose = function () {
  54250. if (this._buffer) {
  54251. this._buffer.dispose();
  54252. this._buffer = null;
  54253. }
  54254. if (this._indexBuffer) {
  54255. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54256. this._indexBuffer = null;
  54257. }
  54258. if (this._spriteTexture) {
  54259. this._spriteTexture.dispose();
  54260. this._spriteTexture = null;
  54261. }
  54262. // Remove from scene
  54263. var index = this._scene.spriteManagers.indexOf(this);
  54264. this._scene.spriteManagers.splice(index, 1);
  54265. // Callback
  54266. this.onDisposeObservable.notifyObservers(this);
  54267. this.onDisposeObservable.clear();
  54268. };
  54269. return SpriteManager;
  54270. }());
  54271. BABYLON.SpriteManager = SpriteManager;
  54272. })(BABYLON || (BABYLON = {}));
  54273. //# sourceMappingURL=babylon.spriteManager.js.map
  54274. var BABYLON;
  54275. (function (BABYLON) {
  54276. var Sprite = /** @class */ (function () {
  54277. function Sprite(name, manager) {
  54278. this.name = name;
  54279. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54280. this.width = 1.0;
  54281. this.height = 1.0;
  54282. this.angle = 0;
  54283. this.cellIndex = 0;
  54284. this.invertU = 0;
  54285. this.invertV = 0;
  54286. this.animations = new Array();
  54287. this.isPickable = false;
  54288. this._animationStarted = false;
  54289. this._loopAnimation = false;
  54290. this._fromIndex = 0;
  54291. this._toIndex = 0;
  54292. this._delay = 0;
  54293. this._direction = 1;
  54294. this._time = 0;
  54295. this._manager = manager;
  54296. this._manager.sprites.push(this);
  54297. this.position = BABYLON.Vector3.Zero();
  54298. }
  54299. Object.defineProperty(Sprite.prototype, "size", {
  54300. get: function () {
  54301. return this.width;
  54302. },
  54303. set: function (value) {
  54304. this.width = value;
  54305. this.height = value;
  54306. },
  54307. enumerable: true,
  54308. configurable: true
  54309. });
  54310. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54311. this._fromIndex = from;
  54312. this._toIndex = to;
  54313. this._loopAnimation = loop;
  54314. this._delay = delay;
  54315. this._animationStarted = true;
  54316. this._direction = from < to ? 1 : -1;
  54317. this.cellIndex = from;
  54318. this._time = 0;
  54319. this._onAnimationEnd = onAnimationEnd;
  54320. };
  54321. Sprite.prototype.stopAnimation = function () {
  54322. this._animationStarted = false;
  54323. };
  54324. Sprite.prototype._animate = function (deltaTime) {
  54325. if (!this._animationStarted)
  54326. return;
  54327. this._time += deltaTime;
  54328. if (this._time > this._delay) {
  54329. this._time = this._time % this._delay;
  54330. this.cellIndex += this._direction;
  54331. if (this.cellIndex > this._toIndex) {
  54332. if (this._loopAnimation) {
  54333. this.cellIndex = this._fromIndex;
  54334. }
  54335. else {
  54336. this.cellIndex = this._toIndex;
  54337. this._animationStarted = false;
  54338. if (this._onAnimationEnd) {
  54339. this._onAnimationEnd();
  54340. }
  54341. if (this.disposeWhenFinishedAnimating) {
  54342. this.dispose();
  54343. }
  54344. }
  54345. }
  54346. }
  54347. };
  54348. Sprite.prototype.dispose = function () {
  54349. for (var i = 0; i < this._manager.sprites.length; i++) {
  54350. if (this._manager.sprites[i] == this) {
  54351. this._manager.sprites.splice(i, 1);
  54352. }
  54353. }
  54354. };
  54355. return Sprite;
  54356. }());
  54357. BABYLON.Sprite = Sprite;
  54358. })(BABYLON || (BABYLON = {}));
  54359. //# sourceMappingURL=babylon.sprite.js.map
  54360. var BABYLON;
  54361. (function (BABYLON) {
  54362. var IntersectionInfo = /** @class */ (function () {
  54363. function IntersectionInfo(bu, bv, distance) {
  54364. this.bu = bu;
  54365. this.bv = bv;
  54366. this.distance = distance;
  54367. this.faceId = 0;
  54368. this.subMeshId = 0;
  54369. }
  54370. return IntersectionInfo;
  54371. }());
  54372. BABYLON.IntersectionInfo = IntersectionInfo;
  54373. var PickingInfo = /** @class */ (function () {
  54374. function PickingInfo() {
  54375. this.hit = false;
  54376. this.distance = 0;
  54377. this.pickedPoint = null;
  54378. this.pickedMesh = null;
  54379. this.bu = 0;
  54380. this.bv = 0;
  54381. this.faceId = -1;
  54382. this.subMeshId = 0;
  54383. this.pickedSprite = null;
  54384. }
  54385. // Methods
  54386. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54387. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54388. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54389. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54390. return null;
  54391. }
  54392. var indices = this.pickedMesh.getIndices();
  54393. if (!indices) {
  54394. return null;
  54395. }
  54396. var result;
  54397. if (useVerticesNormals) {
  54398. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54399. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54400. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54401. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54402. normal0 = normal0.scale(this.bu);
  54403. normal1 = normal1.scale(this.bv);
  54404. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54405. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54406. }
  54407. else {
  54408. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54409. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54410. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54411. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54412. var p1p2 = vertex1.subtract(vertex2);
  54413. var p3p2 = vertex3.subtract(vertex2);
  54414. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54415. }
  54416. if (useWorldCoordinates) {
  54417. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54418. }
  54419. return BABYLON.Vector3.Normalize(result);
  54420. };
  54421. PickingInfo.prototype.getTextureCoordinates = function () {
  54422. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54423. return null;
  54424. }
  54425. var indices = this.pickedMesh.getIndices();
  54426. if (!indices) {
  54427. return null;
  54428. }
  54429. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54430. if (!uvs) {
  54431. return null;
  54432. }
  54433. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54434. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54435. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54436. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54437. uv1 = uv1.scale(this.bu);
  54438. uv2 = uv2.scale(this.bv);
  54439. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54440. };
  54441. return PickingInfo;
  54442. }());
  54443. BABYLON.PickingInfo = PickingInfo;
  54444. })(BABYLON || (BABYLON = {}));
  54445. //# sourceMappingURL=babylon.pickingInfo.js.map
  54446. var BABYLON;
  54447. (function (BABYLON) {
  54448. var Ray = /** @class */ (function () {
  54449. function Ray(origin, direction, length) {
  54450. if (length === void 0) { length = Number.MAX_VALUE; }
  54451. this.origin = origin;
  54452. this.direction = direction;
  54453. this.length = length;
  54454. }
  54455. // Methods
  54456. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54457. var d = 0.0;
  54458. var maxValue = Number.MAX_VALUE;
  54459. var inv;
  54460. var min;
  54461. var max;
  54462. var temp;
  54463. if (Math.abs(this.direction.x) < 0.0000001) {
  54464. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54465. return false;
  54466. }
  54467. }
  54468. else {
  54469. inv = 1.0 / this.direction.x;
  54470. min = (minimum.x - this.origin.x) * inv;
  54471. max = (maximum.x - this.origin.x) * inv;
  54472. if (max === -Infinity) {
  54473. max = Infinity;
  54474. }
  54475. if (min > max) {
  54476. temp = min;
  54477. min = max;
  54478. max = temp;
  54479. }
  54480. d = Math.max(min, d);
  54481. maxValue = Math.min(max, maxValue);
  54482. if (d > maxValue) {
  54483. return false;
  54484. }
  54485. }
  54486. if (Math.abs(this.direction.y) < 0.0000001) {
  54487. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54488. return false;
  54489. }
  54490. }
  54491. else {
  54492. inv = 1.0 / this.direction.y;
  54493. min = (minimum.y - this.origin.y) * inv;
  54494. max = (maximum.y - this.origin.y) * inv;
  54495. if (max === -Infinity) {
  54496. max = Infinity;
  54497. }
  54498. if (min > max) {
  54499. temp = min;
  54500. min = max;
  54501. max = temp;
  54502. }
  54503. d = Math.max(min, d);
  54504. maxValue = Math.min(max, maxValue);
  54505. if (d > maxValue) {
  54506. return false;
  54507. }
  54508. }
  54509. if (Math.abs(this.direction.z) < 0.0000001) {
  54510. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54511. return false;
  54512. }
  54513. }
  54514. else {
  54515. inv = 1.0 / this.direction.z;
  54516. min = (minimum.z - this.origin.z) * inv;
  54517. max = (maximum.z - this.origin.z) * inv;
  54518. if (max === -Infinity) {
  54519. max = Infinity;
  54520. }
  54521. if (min > max) {
  54522. temp = min;
  54523. min = max;
  54524. max = temp;
  54525. }
  54526. d = Math.max(min, d);
  54527. maxValue = Math.min(max, maxValue);
  54528. if (d > maxValue) {
  54529. return false;
  54530. }
  54531. }
  54532. return true;
  54533. };
  54534. Ray.prototype.intersectsBox = function (box) {
  54535. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54536. };
  54537. Ray.prototype.intersectsSphere = function (sphere) {
  54538. var x = sphere.center.x - this.origin.x;
  54539. var y = sphere.center.y - this.origin.y;
  54540. var z = sphere.center.z - this.origin.z;
  54541. var pyth = (x * x) + (y * y) + (z * z);
  54542. var rr = sphere.radius * sphere.radius;
  54543. if (pyth <= rr) {
  54544. return true;
  54545. }
  54546. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54547. if (dot < 0.0) {
  54548. return false;
  54549. }
  54550. var temp = pyth - (dot * dot);
  54551. return temp <= rr;
  54552. };
  54553. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54554. if (!this._edge1) {
  54555. this._edge1 = BABYLON.Vector3.Zero();
  54556. this._edge2 = BABYLON.Vector3.Zero();
  54557. this._pvec = BABYLON.Vector3.Zero();
  54558. this._tvec = BABYLON.Vector3.Zero();
  54559. this._qvec = BABYLON.Vector3.Zero();
  54560. }
  54561. vertex1.subtractToRef(vertex0, this._edge1);
  54562. vertex2.subtractToRef(vertex0, this._edge2);
  54563. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54564. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54565. if (det === 0) {
  54566. return null;
  54567. }
  54568. var invdet = 1 / det;
  54569. this.origin.subtractToRef(vertex0, this._tvec);
  54570. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54571. if (bu < 0 || bu > 1.0) {
  54572. return null;
  54573. }
  54574. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54575. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54576. if (bv < 0 || bu + bv > 1.0) {
  54577. return null;
  54578. }
  54579. //check if the distance is longer than the predefined length.
  54580. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54581. if (distance > this.length) {
  54582. return null;
  54583. }
  54584. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54585. };
  54586. Ray.prototype.intersectsPlane = function (plane) {
  54587. var distance;
  54588. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54589. if (Math.abs(result1) < 9.99999997475243E-07) {
  54590. return null;
  54591. }
  54592. else {
  54593. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54594. distance = (-plane.d - result2) / result1;
  54595. if (distance < 0.0) {
  54596. if (distance < -9.99999997475243E-07) {
  54597. return null;
  54598. }
  54599. else {
  54600. return 0;
  54601. }
  54602. }
  54603. return distance;
  54604. }
  54605. };
  54606. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54607. var tm = BABYLON.Tmp.Matrix[0];
  54608. mesh.getWorldMatrix().invertToRef(tm);
  54609. if (this._tmpRay) {
  54610. Ray.TransformToRef(this, tm, this._tmpRay);
  54611. }
  54612. else {
  54613. this._tmpRay = Ray.Transform(this, tm);
  54614. }
  54615. return mesh.intersects(this._tmpRay, fastCheck);
  54616. };
  54617. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54618. if (results) {
  54619. results.length = 0;
  54620. }
  54621. else {
  54622. results = [];
  54623. }
  54624. for (var i = 0; i < meshes.length; i++) {
  54625. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54626. if (pickInfo.hit) {
  54627. results.push(pickInfo);
  54628. }
  54629. }
  54630. results.sort(this._comparePickingInfo);
  54631. return results;
  54632. };
  54633. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54634. if (pickingInfoA.distance < pickingInfoB.distance) {
  54635. return -1;
  54636. }
  54637. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54638. return 1;
  54639. }
  54640. else {
  54641. return 0;
  54642. }
  54643. };
  54644. /**
  54645. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54646. * @param sega the first point of the segment to test the intersection against
  54647. * @param segb the second point of the segment to test the intersection against
  54648. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54649. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54650. */
  54651. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54652. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54653. var u = segb.subtract(sega);
  54654. var v = rsegb.subtract(this.origin);
  54655. var w = sega.subtract(this.origin);
  54656. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54657. var b = BABYLON.Vector3.Dot(u, v);
  54658. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54659. var d = BABYLON.Vector3.Dot(u, w);
  54660. var e = BABYLON.Vector3.Dot(v, w);
  54661. var D = a * c - b * b; // always >= 0
  54662. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54663. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54664. // compute the line parameters of the two closest points
  54665. if (D < Ray.smallnum) { // the lines are almost parallel
  54666. sN = 0.0; // force using point P0 on segment S1
  54667. sD = 1.0; // to prevent possible division by 0.0 later
  54668. tN = e;
  54669. tD = c;
  54670. }
  54671. else { // get the closest points on the infinite lines
  54672. sN = (b * e - c * d);
  54673. tN = (a * e - b * d);
  54674. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54675. sN = 0.0;
  54676. tN = e;
  54677. tD = c;
  54678. }
  54679. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54680. sN = sD;
  54681. tN = e + b;
  54682. tD = c;
  54683. }
  54684. }
  54685. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54686. tN = 0.0;
  54687. // recompute sc for this edge
  54688. if (-d < 0.0) {
  54689. sN = 0.0;
  54690. }
  54691. else if (-d > a)
  54692. sN = sD;
  54693. else {
  54694. sN = -d;
  54695. sD = a;
  54696. }
  54697. }
  54698. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54699. tN = tD;
  54700. // recompute sc for this edge
  54701. if ((-d + b) < 0.0) {
  54702. sN = 0;
  54703. }
  54704. else if ((-d + b) > a) {
  54705. sN = sD;
  54706. }
  54707. else {
  54708. sN = (-d + b);
  54709. sD = a;
  54710. }
  54711. }
  54712. // finally do the division to get sc and tc
  54713. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54714. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54715. // get the difference of the two closest points
  54716. var qtc = v.multiplyByFloats(tc, tc, tc);
  54717. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54718. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54719. if (isIntersected) {
  54720. return qtc.length();
  54721. }
  54722. return -1;
  54723. };
  54724. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54725. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54726. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54727. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54728. this.direction.normalize();
  54729. return this;
  54730. };
  54731. // Statics
  54732. Ray.Zero = function () {
  54733. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54734. };
  54735. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54736. var result = Ray.Zero();
  54737. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54738. };
  54739. /**
  54740. * 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
  54741. * transformed to the given world matrix.
  54742. * @param origin The origin point
  54743. * @param end The end point
  54744. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54745. */
  54746. Ray.CreateNewFromTo = function (origin, end, world) {
  54747. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54748. var direction = end.subtract(origin);
  54749. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54750. direction.normalize();
  54751. return Ray.Transform(new Ray(origin, direction, length), world);
  54752. };
  54753. Ray.Transform = function (ray, matrix) {
  54754. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54755. Ray.TransformToRef(ray, matrix, result);
  54756. return result;
  54757. };
  54758. Ray.TransformToRef = function (ray, matrix, result) {
  54759. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54760. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54761. result.length = ray.length;
  54762. var dir = result.direction;
  54763. var len = dir.length();
  54764. if (!(len === 0 || len === 1)) {
  54765. var num = 1.0 / len;
  54766. dir.x *= num;
  54767. dir.y *= num;
  54768. dir.z *= num;
  54769. result.length *= len;
  54770. }
  54771. };
  54772. Ray.smallnum = 0.00000001;
  54773. Ray.rayl = 10e8;
  54774. return Ray;
  54775. }());
  54776. BABYLON.Ray = Ray;
  54777. })(BABYLON || (BABYLON = {}));
  54778. //# sourceMappingURL=babylon.ray.js.map
  54779. var BABYLON;
  54780. (function (BABYLON) {
  54781. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54782. if (boxMin.x > sphereCenter.x + sphereRadius)
  54783. return false;
  54784. if (sphereCenter.x - sphereRadius > boxMax.x)
  54785. return false;
  54786. if (boxMin.y > sphereCenter.y + sphereRadius)
  54787. return false;
  54788. if (sphereCenter.y - sphereRadius > boxMax.y)
  54789. return false;
  54790. if (boxMin.z > sphereCenter.z + sphereRadius)
  54791. return false;
  54792. if (sphereCenter.z - sphereRadius > boxMax.z)
  54793. return false;
  54794. return true;
  54795. };
  54796. var getLowestRoot = (function () {
  54797. var result = { root: 0, found: false };
  54798. return function (a, b, c, maxR) {
  54799. result.root = 0;
  54800. result.found = false;
  54801. var determinant = b * b - 4.0 * a * c;
  54802. if (determinant < 0)
  54803. return result;
  54804. var sqrtD = Math.sqrt(determinant);
  54805. var r1 = (-b - sqrtD) / (2.0 * a);
  54806. var r2 = (-b + sqrtD) / (2.0 * a);
  54807. if (r1 > r2) {
  54808. var temp = r2;
  54809. r2 = r1;
  54810. r1 = temp;
  54811. }
  54812. if (r1 > 0 && r1 < maxR) {
  54813. result.root = r1;
  54814. result.found = true;
  54815. return result;
  54816. }
  54817. if (r2 > 0 && r2 < maxR) {
  54818. result.root = r2;
  54819. result.found = true;
  54820. return result;
  54821. }
  54822. return result;
  54823. };
  54824. })();
  54825. var Collider = /** @class */ (function () {
  54826. function Collider() {
  54827. this._collisionPoint = BABYLON.Vector3.Zero();
  54828. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54829. this._tempVector = BABYLON.Vector3.Zero();
  54830. this._tempVector2 = BABYLON.Vector3.Zero();
  54831. this._tempVector3 = BABYLON.Vector3.Zero();
  54832. this._tempVector4 = BABYLON.Vector3.Zero();
  54833. this._edge = BABYLON.Vector3.Zero();
  54834. this._baseToVertex = BABYLON.Vector3.Zero();
  54835. this._destinationPoint = BABYLON.Vector3.Zero();
  54836. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54837. this._displacementVector = BABYLON.Vector3.Zero();
  54838. this._radius = BABYLON.Vector3.One();
  54839. this._retry = 0;
  54840. this._basePointWorld = BABYLON.Vector3.Zero();
  54841. this._velocityWorld = BABYLON.Vector3.Zero();
  54842. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54843. this._collisionMask = -1;
  54844. }
  54845. Object.defineProperty(Collider.prototype, "collisionMask", {
  54846. get: function () {
  54847. return this._collisionMask;
  54848. },
  54849. set: function (mask) {
  54850. this._collisionMask = !isNaN(mask) ? mask : -1;
  54851. },
  54852. enumerable: true,
  54853. configurable: true
  54854. });
  54855. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54856. /**
  54857. * Gets the plane normal used to compute the sliding response (in local space)
  54858. */
  54859. get: function () {
  54860. return this._slidePlaneNormal;
  54861. },
  54862. enumerable: true,
  54863. configurable: true
  54864. });
  54865. // Methods
  54866. Collider.prototype._initialize = function (source, dir, e) {
  54867. this._velocity = dir;
  54868. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54869. this._basePoint = source;
  54870. source.multiplyToRef(this._radius, this._basePointWorld);
  54871. dir.multiplyToRef(this._radius, this._velocityWorld);
  54872. this._velocityWorldLength = this._velocityWorld.length();
  54873. this._epsilon = e;
  54874. this.collisionFound = false;
  54875. };
  54876. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54877. pa.subtractToRef(point, this._tempVector);
  54878. pb.subtractToRef(point, this._tempVector2);
  54879. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54880. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54881. if (d < 0)
  54882. return false;
  54883. pc.subtractToRef(point, this._tempVector3);
  54884. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54885. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54886. if (d < 0)
  54887. return false;
  54888. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54889. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54890. return d >= 0;
  54891. };
  54892. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54893. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54894. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54895. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54896. return false;
  54897. }
  54898. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54899. return false;
  54900. return true;
  54901. };
  54902. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54903. var t0;
  54904. var embeddedInPlane = false;
  54905. //defensive programming, actually not needed.
  54906. if (!trianglePlaneArray) {
  54907. trianglePlaneArray = [];
  54908. }
  54909. if (!trianglePlaneArray[faceIndex]) {
  54910. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54911. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54912. }
  54913. var trianglePlane = trianglePlaneArray[faceIndex];
  54914. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54915. return;
  54916. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54917. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54918. if (normalDotVelocity == 0) {
  54919. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54920. return;
  54921. embeddedInPlane = true;
  54922. t0 = 0;
  54923. }
  54924. else {
  54925. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54926. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54927. if (t0 > t1) {
  54928. var temp = t1;
  54929. t1 = t0;
  54930. t0 = temp;
  54931. }
  54932. if (t0 > 1.0 || t1 < 0.0)
  54933. return;
  54934. if (t0 < 0)
  54935. t0 = 0;
  54936. if (t0 > 1.0)
  54937. t0 = 1.0;
  54938. }
  54939. this._collisionPoint.copyFromFloats(0, 0, 0);
  54940. var found = false;
  54941. var t = 1.0;
  54942. if (!embeddedInPlane) {
  54943. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54944. this._velocity.scaleToRef(t0, this._tempVector);
  54945. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54946. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54947. found = true;
  54948. t = t0;
  54949. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54950. }
  54951. }
  54952. if (!found) {
  54953. var velocitySquaredLength = this._velocity.lengthSquared();
  54954. var a = velocitySquaredLength;
  54955. this._basePoint.subtractToRef(p1, this._tempVector);
  54956. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54957. var c = this._tempVector.lengthSquared() - 1.0;
  54958. var lowestRoot = getLowestRoot(a, b, c, t);
  54959. if (lowestRoot.found) {
  54960. t = lowestRoot.root;
  54961. found = true;
  54962. this._collisionPoint.copyFrom(p1);
  54963. }
  54964. this._basePoint.subtractToRef(p2, this._tempVector);
  54965. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54966. c = this._tempVector.lengthSquared() - 1.0;
  54967. lowestRoot = getLowestRoot(a, b, c, t);
  54968. if (lowestRoot.found) {
  54969. t = lowestRoot.root;
  54970. found = true;
  54971. this._collisionPoint.copyFrom(p2);
  54972. }
  54973. this._basePoint.subtractToRef(p3, this._tempVector);
  54974. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54975. c = this._tempVector.lengthSquared() - 1.0;
  54976. lowestRoot = getLowestRoot(a, b, c, t);
  54977. if (lowestRoot.found) {
  54978. t = lowestRoot.root;
  54979. found = true;
  54980. this._collisionPoint.copyFrom(p3);
  54981. }
  54982. p2.subtractToRef(p1, this._edge);
  54983. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54984. var edgeSquaredLength = this._edge.lengthSquared();
  54985. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54986. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54987. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54988. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54989. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54990. lowestRoot = getLowestRoot(a, b, c, t);
  54991. if (lowestRoot.found) {
  54992. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54993. if (f >= 0.0 && f <= 1.0) {
  54994. t = lowestRoot.root;
  54995. found = true;
  54996. this._edge.scaleInPlace(f);
  54997. p1.addToRef(this._edge, this._collisionPoint);
  54998. }
  54999. }
  55000. p3.subtractToRef(p2, this._edge);
  55001. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55002. edgeSquaredLength = this._edge.lengthSquared();
  55003. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55004. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55005. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55006. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55007. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55008. lowestRoot = getLowestRoot(a, b, c, t);
  55009. if (lowestRoot.found) {
  55010. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55011. if (f >= 0.0 && f <= 1.0) {
  55012. t = lowestRoot.root;
  55013. found = true;
  55014. this._edge.scaleInPlace(f);
  55015. p2.addToRef(this._edge, this._collisionPoint);
  55016. }
  55017. }
  55018. p1.subtractToRef(p3, this._edge);
  55019. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55020. edgeSquaredLength = this._edge.lengthSquared();
  55021. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55022. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55023. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55024. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55025. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55026. lowestRoot = getLowestRoot(a, b, c, t);
  55027. if (lowestRoot.found) {
  55028. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55029. if (f >= 0.0 && f <= 1.0) {
  55030. t = lowestRoot.root;
  55031. found = true;
  55032. this._edge.scaleInPlace(f);
  55033. p3.addToRef(this._edge, this._collisionPoint);
  55034. }
  55035. }
  55036. }
  55037. if (found) {
  55038. var distToCollision = t * this._velocity.length();
  55039. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55040. if (!this.intersectionPoint) {
  55041. this.intersectionPoint = this._collisionPoint.clone();
  55042. }
  55043. else {
  55044. this.intersectionPoint.copyFrom(this._collisionPoint);
  55045. }
  55046. this._nearestDistance = distToCollision;
  55047. this.collisionFound = true;
  55048. }
  55049. }
  55050. };
  55051. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55052. for (var i = indexStart; i < indexEnd; i += 3) {
  55053. var p1 = pts[indices[i] - decal];
  55054. var p2 = pts[indices[i + 1] - decal];
  55055. var p3 = pts[indices[i + 2] - decal];
  55056. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55057. }
  55058. };
  55059. Collider.prototype._getResponse = function (pos, vel) {
  55060. pos.addToRef(vel, this._destinationPoint);
  55061. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55062. this._basePoint.addToRef(vel, pos);
  55063. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55064. this._slidePlaneNormal.normalize();
  55065. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55066. pos.addInPlace(this._displacementVector);
  55067. this.intersectionPoint.addInPlace(this._displacementVector);
  55068. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55069. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55070. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55071. };
  55072. return Collider;
  55073. }());
  55074. BABYLON.Collider = Collider;
  55075. })(BABYLON || (BABYLON = {}));
  55076. //# sourceMappingURL=babylon.collider.js.map
  55077. var BABYLON;
  55078. (function (BABYLON) {
  55079. //WebWorker code will be inserted to this variable.
  55080. BABYLON.CollisionWorker = "";
  55081. /** Defines supported task for worker process */
  55082. var WorkerTaskType;
  55083. (function (WorkerTaskType) {
  55084. /** Initialization */
  55085. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55086. /** Update of geometry */
  55087. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55088. /** Evaluate collision */
  55089. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55090. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55091. /** Defines kind of replies returned by worker */
  55092. var WorkerReplyType;
  55093. (function (WorkerReplyType) {
  55094. /** Success */
  55095. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55096. /** Unkown error */
  55097. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55098. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55099. var CollisionCoordinatorWorker = /** @class */ (function () {
  55100. function CollisionCoordinatorWorker() {
  55101. var _this = this;
  55102. this._scaledPosition = BABYLON.Vector3.Zero();
  55103. this._scaledVelocity = BABYLON.Vector3.Zero();
  55104. this.onMeshUpdated = function (transformNode) {
  55105. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55106. };
  55107. this.onGeometryUpdated = function (geometry) {
  55108. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55109. };
  55110. this._afterRender = function () {
  55111. if (!_this._init)
  55112. return;
  55113. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55114. return;
  55115. }
  55116. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55117. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55118. if (_this._runningUpdated > 4) {
  55119. return;
  55120. }
  55121. ++_this._runningUpdated;
  55122. var payload = {
  55123. updatedMeshes: _this._addUpdateMeshesList,
  55124. updatedGeometries: _this._addUpdateGeometriesList,
  55125. removedGeometries: _this._toRemoveGeometryArray,
  55126. removedMeshes: _this._toRemoveMeshesArray
  55127. };
  55128. var message = {
  55129. payload: payload,
  55130. taskType: WorkerTaskType.UPDATE
  55131. };
  55132. var serializable = [];
  55133. for (var id in payload.updatedGeometries) {
  55134. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55135. //prepare transferables
  55136. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55137. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55138. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55139. }
  55140. }
  55141. _this._worker.postMessage(message, serializable);
  55142. _this._addUpdateMeshesList = {};
  55143. _this._addUpdateGeometriesList = {};
  55144. _this._toRemoveGeometryArray = [];
  55145. _this._toRemoveMeshesArray = [];
  55146. };
  55147. this._onMessageFromWorker = function (e) {
  55148. var returnData = e.data;
  55149. if (returnData.error != WorkerReplyType.SUCCESS) {
  55150. //TODO what errors can be returned from the worker?
  55151. BABYLON.Tools.Warn("error returned from worker!");
  55152. return;
  55153. }
  55154. switch (returnData.taskType) {
  55155. case WorkerTaskType.INIT:
  55156. _this._init = true;
  55157. //Update the worked with ALL of the scene's current state
  55158. _this._scene.meshes.forEach(function (mesh) {
  55159. _this.onMeshAdded(mesh);
  55160. });
  55161. _this._scene.getGeometries().forEach(function (geometry) {
  55162. _this.onGeometryAdded(geometry);
  55163. });
  55164. break;
  55165. case WorkerTaskType.UPDATE:
  55166. _this._runningUpdated--;
  55167. break;
  55168. case WorkerTaskType.COLLIDE:
  55169. var returnPayload = returnData.payload;
  55170. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55171. return;
  55172. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55173. if (callback) {
  55174. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55175. if (mesh) {
  55176. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55177. }
  55178. }
  55179. //cleanup
  55180. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55181. break;
  55182. }
  55183. };
  55184. this._collisionsCallbackArray = [];
  55185. this._init = false;
  55186. this._runningUpdated = 0;
  55187. this._addUpdateMeshesList = {};
  55188. this._addUpdateGeometriesList = {};
  55189. this._toRemoveGeometryArray = [];
  55190. this._toRemoveMeshesArray = [];
  55191. }
  55192. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55193. if (!this._init)
  55194. return;
  55195. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55196. return;
  55197. position.divideToRef(collider._radius, this._scaledPosition);
  55198. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55199. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55200. var payload = {
  55201. collider: {
  55202. position: this._scaledPosition.asArray(),
  55203. velocity: this._scaledVelocity.asArray(),
  55204. radius: collider._radius.asArray()
  55205. },
  55206. collisionId: collisionIndex,
  55207. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55208. maximumRetry: maximumRetry
  55209. };
  55210. var message = {
  55211. payload: payload,
  55212. taskType: WorkerTaskType.COLLIDE
  55213. };
  55214. this._worker.postMessage(message);
  55215. };
  55216. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55217. this._scene = scene;
  55218. this._scene.registerAfterRender(this._afterRender);
  55219. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55220. this._worker = new Worker(workerUrl);
  55221. this._worker.onmessage = this._onMessageFromWorker;
  55222. var message = {
  55223. payload: {},
  55224. taskType: WorkerTaskType.INIT
  55225. };
  55226. this._worker.postMessage(message);
  55227. };
  55228. CollisionCoordinatorWorker.prototype.destroy = function () {
  55229. this._scene.unregisterAfterRender(this._afterRender);
  55230. this._worker.terminate();
  55231. };
  55232. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55233. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55234. this.onMeshUpdated(mesh);
  55235. };
  55236. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55237. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55238. };
  55239. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55240. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55241. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55242. this.onGeometryUpdated(geometry);
  55243. };
  55244. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55245. this._toRemoveGeometryArray.push(geometry.id);
  55246. };
  55247. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55248. var submeshes = [];
  55249. if (mesh.subMeshes) {
  55250. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55251. var boundingInfo = sm.getBoundingInfo();
  55252. return {
  55253. position: idx,
  55254. verticesStart: sm.verticesStart,
  55255. verticesCount: sm.verticesCount,
  55256. indexStart: sm.indexStart,
  55257. indexCount: sm.indexCount,
  55258. hasMaterial: !!sm.getMaterial(),
  55259. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55260. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55261. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55262. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55263. };
  55264. });
  55265. }
  55266. var geometryId = null;
  55267. if (mesh instanceof BABYLON.Mesh) {
  55268. var geometry = mesh.geometry;
  55269. geometryId = geometry ? geometry.id : null;
  55270. }
  55271. else if (mesh instanceof BABYLON.InstancedMesh) {
  55272. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55273. geometryId = geometry ? geometry.id : null;
  55274. }
  55275. var boundingInfo = mesh.getBoundingInfo();
  55276. return {
  55277. uniqueId: mesh.uniqueId,
  55278. id: mesh.id,
  55279. name: mesh.name,
  55280. geometryId: geometryId,
  55281. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55282. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55283. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55284. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55285. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55286. subMeshes: submeshes,
  55287. checkCollisions: mesh.checkCollisions
  55288. };
  55289. };
  55290. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55291. return {
  55292. id: geometry.id,
  55293. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55294. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55295. indices: new Uint32Array(geometry.getIndices() || []),
  55296. };
  55297. };
  55298. return CollisionCoordinatorWorker;
  55299. }());
  55300. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55301. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55302. function CollisionCoordinatorLegacy() {
  55303. this._scaledPosition = BABYLON.Vector3.Zero();
  55304. this._scaledVelocity = BABYLON.Vector3.Zero();
  55305. this._finalPosition = BABYLON.Vector3.Zero();
  55306. }
  55307. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55308. position.divideToRef(collider._radius, this._scaledPosition);
  55309. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55310. collider.collidedMesh = null;
  55311. collider._retry = 0;
  55312. collider._initialVelocity = this._scaledVelocity;
  55313. collider._initialPosition = this._scaledPosition;
  55314. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55315. this._finalPosition.multiplyInPlace(collider._radius);
  55316. //run the callback
  55317. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55318. };
  55319. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55320. this._scene = scene;
  55321. };
  55322. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55323. //Legacy need no destruction method.
  55324. };
  55325. //No update in legacy mode
  55326. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55327. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55328. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55329. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55330. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55331. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55332. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55333. if (excludedMesh === void 0) { excludedMesh = null; }
  55334. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55335. if (collider._retry >= maximumRetry) {
  55336. finalPosition.copyFrom(position);
  55337. return;
  55338. }
  55339. // Check if this is a mesh else camera or -1
  55340. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55341. collider._initialize(position, velocity, closeDistance);
  55342. // Check all meshes
  55343. for (var index = 0; index < this._scene.meshes.length; index++) {
  55344. var mesh = this._scene.meshes[index];
  55345. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55346. mesh._checkCollision(collider);
  55347. }
  55348. }
  55349. if (!collider.collisionFound) {
  55350. position.addToRef(velocity, finalPosition);
  55351. return;
  55352. }
  55353. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55354. collider._getResponse(position, velocity);
  55355. }
  55356. if (velocity.length() <= closeDistance) {
  55357. finalPosition.copyFrom(position);
  55358. return;
  55359. }
  55360. collider._retry++;
  55361. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55362. };
  55363. return CollisionCoordinatorLegacy;
  55364. }());
  55365. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55366. })(BABYLON || (BABYLON = {}));
  55367. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55368. var BABYLON;
  55369. (function (BABYLON) {
  55370. /**
  55371. * A particle represents one of the element emitted by a particle system.
  55372. * This is mainly define by its coordinates, direction, velocity and age.
  55373. */
  55374. var Particle = /** @class */ (function () {
  55375. /**
  55376. * Creates a new instance Particle
  55377. * @param particleSystem the particle system the particle belongs to
  55378. */
  55379. function Particle(
  55380. /**
  55381. * particleSystem the particle system the particle belongs to.
  55382. */
  55383. particleSystem) {
  55384. this.particleSystem = particleSystem;
  55385. /**
  55386. * The world position of the particle in the scene.
  55387. */
  55388. this.position = BABYLON.Vector3.Zero();
  55389. /**
  55390. * The world direction of the particle in the scene.
  55391. */
  55392. this.direction = BABYLON.Vector3.Zero();
  55393. /**
  55394. * The color of the particle.
  55395. */
  55396. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55397. /**
  55398. * The color change of the particle per step.
  55399. */
  55400. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55401. /**
  55402. * Defines how long will the life of the particle be.
  55403. */
  55404. this.lifeTime = 1.0;
  55405. /**
  55406. * The current age of the particle.
  55407. */
  55408. this.age = 0;
  55409. /**
  55410. * The current size of the particle.
  55411. */
  55412. this.size = 0;
  55413. /**
  55414. * The current angle of the particle.
  55415. */
  55416. this.angle = 0;
  55417. /**
  55418. * Defines how fast is the angle changing.
  55419. */
  55420. this.angularSpeed = 0;
  55421. /**
  55422. * Defines the cell index used by the particle to be rendered from a sprite.
  55423. */
  55424. this.cellIndex = 0;
  55425. this._currentFrameCounter = 0;
  55426. if (!this.particleSystem.isAnimationSheetEnabled) {
  55427. return;
  55428. }
  55429. this.updateCellInfoFromSystem();
  55430. }
  55431. Particle.prototype.updateCellInfoFromSystem = function () {
  55432. this.cellIndex = this.particleSystem.startSpriteCellID;
  55433. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55434. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55435. }
  55436. else {
  55437. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55438. }
  55439. };
  55440. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55441. // (ageOffset / scaledUpdateSpeed) / available cells
  55442. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55443. this._currentFrameCounter += scaledUpdateSpeed;
  55444. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55445. this._currentFrameCounter = 0;
  55446. this.cellIndex++;
  55447. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55448. this.cellIndex = this.particleSystem.endSpriteCellID;
  55449. }
  55450. }
  55451. };
  55452. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55453. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55454. this.cellIndex++;
  55455. this._currentFrameCounter = 0;
  55456. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55457. if (this.particleSystem.spriteCellLoop) {
  55458. this.cellIndex = this.particleSystem.startSpriteCellID;
  55459. }
  55460. else {
  55461. this.cellIndex = this.particleSystem.endSpriteCellID;
  55462. }
  55463. }
  55464. }
  55465. else {
  55466. this._currentFrameCounter++;
  55467. }
  55468. };
  55469. /**
  55470. * Copy the properties of particle to another one.
  55471. * @param other the particle to copy the information to.
  55472. */
  55473. Particle.prototype.copyTo = function (other) {
  55474. other.position.copyFrom(this.position);
  55475. other.direction.copyFrom(this.direction);
  55476. other.color.copyFrom(this.color);
  55477. other.colorStep.copyFrom(this.colorStep);
  55478. other.lifeTime = this.lifeTime;
  55479. other.age = this.age;
  55480. other.size = this.size;
  55481. other.angle = this.angle;
  55482. other.angularSpeed = this.angularSpeed;
  55483. other.particleSystem = this.particleSystem;
  55484. other.cellIndex = this.cellIndex;
  55485. };
  55486. return Particle;
  55487. }());
  55488. BABYLON.Particle = Particle;
  55489. })(BABYLON || (BABYLON = {}));
  55490. //# sourceMappingURL=babylon.particle.js.map
  55491. var BABYLON;
  55492. (function (BABYLON) {
  55493. /**
  55494. * This represents a particle system in Babylon.
  55495. * 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.
  55496. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55497. * @example https://doc.babylonjs.com/babylon101/particles
  55498. */
  55499. var ParticleSystem = /** @class */ (function () {
  55500. /**
  55501. * Instantiates a particle system.
  55502. * 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.
  55503. * @param name The name of the particle system
  55504. * @param capacity The max number of particles alive at the same time
  55505. * @param scene The scene the particle system belongs to
  55506. * @param customEffect a custom effect used to change the way particles are rendered by default
  55507. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55508. * @param epsilon Offset used to render the particles
  55509. */
  55510. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55511. if (customEffect === void 0) { customEffect = null; }
  55512. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55513. if (epsilon === void 0) { epsilon = 0.01; }
  55514. var _this = this;
  55515. /**
  55516. * List of animations used by the particle system.
  55517. */
  55518. this.animations = [];
  55519. /**
  55520. * The rendering group used by the Particle system to chose when to render.
  55521. */
  55522. this.renderingGroupId = 0;
  55523. /**
  55524. * The emitter represents the Mesh or position we are attaching the particle system to.
  55525. */
  55526. this.emitter = null;
  55527. /**
  55528. * The maximum number of particles to emit per frame
  55529. */
  55530. this.emitRate = 10;
  55531. /**
  55532. * If you want to launch only a few particles at once, that can be done, as well.
  55533. */
  55534. this.manualEmitCount = -1;
  55535. /**
  55536. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55537. */
  55538. this.updateSpeed = 0.01;
  55539. /**
  55540. * The amount of time the particle system is running (depends of the overall update speed).
  55541. */
  55542. this.targetStopDuration = 0;
  55543. /**
  55544. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55545. */
  55546. this.disposeOnStop = false;
  55547. /**
  55548. * Minimum power of emitting particles.
  55549. */
  55550. this.minEmitPower = 1;
  55551. /**
  55552. * Maximum power of emitting particles.
  55553. */
  55554. this.maxEmitPower = 1;
  55555. /**
  55556. * Minimum life time of emitting particles.
  55557. */
  55558. this.minLifeTime = 1;
  55559. /**
  55560. * Maximum life time of emitting particles.
  55561. */
  55562. this.maxLifeTime = 1;
  55563. /**
  55564. * Minimum Size of emitting particles.
  55565. */
  55566. this.minSize = 1;
  55567. /**
  55568. * Maximum Size of emitting particles.
  55569. */
  55570. this.maxSize = 1;
  55571. /**
  55572. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55573. */
  55574. this.minAngularSpeed = 0;
  55575. /**
  55576. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55577. */
  55578. this.maxAngularSpeed = 0;
  55579. /**
  55580. * The layer mask we are rendering the particles through.
  55581. */
  55582. this.layerMask = 0x0FFFFFFF;
  55583. /**
  55584. * This can help using your own shader to render the particle system.
  55585. * The according effect will be created
  55586. */
  55587. this.customShader = null;
  55588. /**
  55589. * By default particle system starts as soon as they are created. This prevents the
  55590. * automatic start to happen and let you decide when to start emitting particles.
  55591. */
  55592. this.preventAutoStart = false;
  55593. /**
  55594. * Callback triggered when the particle animation is ending.
  55595. */
  55596. this.onAnimationEnd = null;
  55597. /**
  55598. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55599. */
  55600. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55601. /**
  55602. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55603. * to override the particles.
  55604. */
  55605. this.forceDepthWrite = false;
  55606. /**
  55607. * You can use gravity if you want to give an orientation to your particles.
  55608. */
  55609. this.gravity = BABYLON.Vector3.Zero();
  55610. /**
  55611. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55612. */
  55613. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55614. /**
  55615. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55616. */
  55617. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55618. /**
  55619. * Color the particle will have at the end of its lifetime.
  55620. */
  55621. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55622. /**
  55623. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55624. */
  55625. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55626. /**
  55627. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55628. */
  55629. this.spriteCellLoop = true;
  55630. /**
  55631. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55632. */
  55633. this.spriteCellChangeSpeed = 0;
  55634. /**
  55635. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55636. */
  55637. this.startSpriteCellID = 0;
  55638. /**
  55639. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55640. */
  55641. this.endSpriteCellID = 0;
  55642. /**
  55643. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55644. */
  55645. this.spriteCellWidth = 0;
  55646. /**
  55647. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55648. */
  55649. this.spriteCellHeight = 0;
  55650. /**
  55651. * An event triggered when the system is disposed.
  55652. */
  55653. this.onDisposeObservable = new BABYLON.Observable();
  55654. this._particles = new Array();
  55655. this._stockParticles = new Array();
  55656. this._newPartsExcess = 0;
  55657. this._vertexBuffers = {};
  55658. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55659. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55660. this._scaledDirection = BABYLON.Vector3.Zero();
  55661. this._scaledGravity = BABYLON.Vector3.Zero();
  55662. this._currentRenderId = -1;
  55663. this._started = false;
  55664. this._stopped = false;
  55665. this._actualFrame = 0;
  55666. this._vertexBufferSize = 11;
  55667. // start of sub system methods
  55668. /**
  55669. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55670. * Its lifetime will start back at 0.
  55671. */
  55672. this.recycleParticle = function (particle) {
  55673. var lastParticle = _this._particles.pop();
  55674. if (lastParticle !== particle) {
  55675. lastParticle.copyTo(particle);
  55676. }
  55677. _this._stockParticles.push(lastParticle);
  55678. };
  55679. this._createParticle = function () {
  55680. var particle;
  55681. if (_this._stockParticles.length !== 0) {
  55682. particle = _this._stockParticles.pop();
  55683. particle.age = 0;
  55684. particle.cellIndex = _this.startSpriteCellID;
  55685. }
  55686. else {
  55687. particle = new BABYLON.Particle(_this);
  55688. }
  55689. return particle;
  55690. };
  55691. this._emitFromParticle = function (particle) {
  55692. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55693. return;
  55694. }
  55695. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55696. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55697. subSystem._rootParticleSystem = _this;
  55698. _this.activeSubSystems.push(subSystem);
  55699. subSystem.start();
  55700. };
  55701. this._appendParticleVertexes = null;
  55702. this.id = name;
  55703. this.name = name;
  55704. this._capacity = capacity;
  55705. this._epsilon = epsilon;
  55706. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55707. if (isAnimationSheetEnabled) {
  55708. this._vertexBufferSize = 12;
  55709. }
  55710. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55711. this._customEffect = customEffect;
  55712. scene.particleSystems.push(this);
  55713. this._createIndexBuffer();
  55714. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55715. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55716. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55717. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55718. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55719. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55720. if (this._isAnimationSheetEnabled) {
  55721. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55722. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55723. }
  55724. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55725. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55726. this._vertexBuffers["options"] = options;
  55727. // Default emitter type
  55728. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55729. this.updateFunction = function (particles) {
  55730. for (var index = 0; index < particles.length; index++) {
  55731. var particle = particles[index];
  55732. particle.age += _this._scaledUpdateSpeed;
  55733. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55734. _this._emitFromParticle(particle);
  55735. _this.recycleParticle(particle);
  55736. index--;
  55737. continue;
  55738. }
  55739. else {
  55740. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55741. particle.color.addInPlace(_this._scaledColorStep);
  55742. if (particle.color.a < 0)
  55743. particle.color.a = 0;
  55744. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55745. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55746. particle.position.addInPlace(_this._scaledDirection);
  55747. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55748. particle.direction.addInPlace(_this._scaledGravity);
  55749. if (_this._isAnimationSheetEnabled) {
  55750. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55751. }
  55752. }
  55753. }
  55754. };
  55755. }
  55756. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55757. /**
  55758. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55759. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55760. */
  55761. get: function () {
  55762. if (this.particleEmitterType.direction1) {
  55763. return this.particleEmitterType.direction1;
  55764. }
  55765. return BABYLON.Vector3.Zero();
  55766. },
  55767. set: function (value) {
  55768. if (this.particleEmitterType.direction1) {
  55769. this.particleEmitterType.direction1 = value;
  55770. }
  55771. },
  55772. enumerable: true,
  55773. configurable: true
  55774. });
  55775. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55776. /**
  55777. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55778. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55779. */
  55780. get: function () {
  55781. if (this.particleEmitterType.direction2) {
  55782. return this.particleEmitterType.direction2;
  55783. }
  55784. return BABYLON.Vector3.Zero();
  55785. },
  55786. set: function (value) {
  55787. if (this.particleEmitterType.direction2) {
  55788. this.particleEmitterType.direction2 = value;
  55789. }
  55790. },
  55791. enumerable: true,
  55792. configurable: true
  55793. });
  55794. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55795. /**
  55796. * 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.
  55797. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55798. */
  55799. get: function () {
  55800. if (this.particleEmitterType.minEmitBox) {
  55801. return this.particleEmitterType.minEmitBox;
  55802. }
  55803. return BABYLON.Vector3.Zero();
  55804. },
  55805. set: function (value) {
  55806. if (this.particleEmitterType.minEmitBox) {
  55807. this.particleEmitterType.minEmitBox = value;
  55808. }
  55809. },
  55810. enumerable: true,
  55811. configurable: true
  55812. });
  55813. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55814. /**
  55815. * 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.
  55816. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55817. */
  55818. get: function () {
  55819. if (this.particleEmitterType.maxEmitBox) {
  55820. return this.particleEmitterType.maxEmitBox;
  55821. }
  55822. return BABYLON.Vector3.Zero();
  55823. },
  55824. set: function (value) {
  55825. if (this.particleEmitterType.maxEmitBox) {
  55826. this.particleEmitterType.maxEmitBox = value;
  55827. }
  55828. },
  55829. enumerable: true,
  55830. configurable: true
  55831. });
  55832. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55833. /**
  55834. * Sets a callback that will be triggered when the system is disposed.
  55835. */
  55836. set: function (callback) {
  55837. if (this._onDisposeObserver) {
  55838. this.onDisposeObservable.remove(this._onDisposeObserver);
  55839. }
  55840. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55841. },
  55842. enumerable: true,
  55843. configurable: true
  55844. });
  55845. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55846. /**
  55847. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55848. */
  55849. get: function () {
  55850. return this._isAnimationSheetEnabled;
  55851. },
  55852. enumerable: true,
  55853. configurable: true
  55854. });
  55855. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55856. //end of Sub-emitter
  55857. /**
  55858. * Gets the current list of active particles
  55859. */
  55860. get: function () {
  55861. return this._particles;
  55862. },
  55863. enumerable: true,
  55864. configurable: true
  55865. });
  55866. /**
  55867. * Returns the string "ParticleSystem"
  55868. * @returns a string containing the class name
  55869. */
  55870. ParticleSystem.prototype.getClassName = function () {
  55871. return "ParticleSystem";
  55872. };
  55873. ParticleSystem.prototype._createIndexBuffer = function () {
  55874. var indices = [];
  55875. var index = 0;
  55876. for (var count = 0; count < this._capacity; count++) {
  55877. indices.push(index);
  55878. indices.push(index + 1);
  55879. indices.push(index + 2);
  55880. indices.push(index);
  55881. indices.push(index + 2);
  55882. indices.push(index + 3);
  55883. index += 4;
  55884. }
  55885. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55886. };
  55887. /**
  55888. * Gets the maximum number of particles active at the same time.
  55889. * @returns The max number of active particles.
  55890. */
  55891. ParticleSystem.prototype.getCapacity = function () {
  55892. return this._capacity;
  55893. };
  55894. /**
  55895. * Gets Wether there are still active particles in the system.
  55896. * @returns True if it is alive, otherwise false.
  55897. */
  55898. ParticleSystem.prototype.isAlive = function () {
  55899. return this._alive;
  55900. };
  55901. /**
  55902. * Gets Wether the system has been started.
  55903. * @returns True if it has been started, otherwise false.
  55904. */
  55905. ParticleSystem.prototype.isStarted = function () {
  55906. return this._started;
  55907. };
  55908. /**
  55909. * Starts the particle system and begins to emit.
  55910. */
  55911. ParticleSystem.prototype.start = function () {
  55912. this._started = true;
  55913. this._stopped = false;
  55914. this._actualFrame = 0;
  55915. if (this.subEmitters && this.subEmitters.length != 0) {
  55916. this.activeSubSystems = new Array();
  55917. }
  55918. };
  55919. /**
  55920. * Stops the particle system.
  55921. * @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.
  55922. */
  55923. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55924. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55925. this._stopped = true;
  55926. if (stopSubEmitters) {
  55927. this._stopSubEmitters();
  55928. }
  55929. };
  55930. // animation sheet
  55931. /**
  55932. * Remove all active particles
  55933. */
  55934. ParticleSystem.prototype.reset = function () {
  55935. this._stockParticles = [];
  55936. this._particles = [];
  55937. };
  55938. /**
  55939. * @hidden (for internal use only)
  55940. */
  55941. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55942. var offset = index * this._vertexBufferSize;
  55943. this._vertexData[offset] = particle.position.x;
  55944. this._vertexData[offset + 1] = particle.position.y;
  55945. this._vertexData[offset + 2] = particle.position.z;
  55946. this._vertexData[offset + 3] = particle.color.r;
  55947. this._vertexData[offset + 4] = particle.color.g;
  55948. this._vertexData[offset + 5] = particle.color.b;
  55949. this._vertexData[offset + 6] = particle.color.a;
  55950. this._vertexData[offset + 7] = particle.angle;
  55951. this._vertexData[offset + 8] = particle.size;
  55952. this._vertexData[offset + 9] = offsetX;
  55953. this._vertexData[offset + 10] = offsetY;
  55954. };
  55955. /**
  55956. * @hidden (for internal use only)
  55957. */
  55958. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55959. if (offsetX === 0)
  55960. offsetX = this._epsilon;
  55961. else if (offsetX === 1)
  55962. offsetX = 1 - this._epsilon;
  55963. if (offsetY === 0)
  55964. offsetY = this._epsilon;
  55965. else if (offsetY === 1)
  55966. offsetY = 1 - this._epsilon;
  55967. var offset = index * this._vertexBufferSize;
  55968. this._vertexData[offset] = particle.position.x;
  55969. this._vertexData[offset + 1] = particle.position.y;
  55970. this._vertexData[offset + 2] = particle.position.z;
  55971. this._vertexData[offset + 3] = particle.color.r;
  55972. this._vertexData[offset + 4] = particle.color.g;
  55973. this._vertexData[offset + 5] = particle.color.b;
  55974. this._vertexData[offset + 6] = particle.color.a;
  55975. this._vertexData[offset + 7] = particle.angle;
  55976. this._vertexData[offset + 8] = particle.size;
  55977. this._vertexData[offset + 9] = offsetX;
  55978. this._vertexData[offset + 10] = offsetY;
  55979. this._vertexData[offset + 11] = particle.cellIndex;
  55980. };
  55981. ParticleSystem.prototype._stopSubEmitters = function () {
  55982. if (!this.activeSubSystems) {
  55983. return;
  55984. }
  55985. this.activeSubSystems.forEach(function (subSystem) {
  55986. subSystem.stop(true);
  55987. });
  55988. this.activeSubSystems = new Array();
  55989. };
  55990. ParticleSystem.prototype._removeFromRoot = function () {
  55991. if (!this._rootParticleSystem) {
  55992. return;
  55993. }
  55994. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55995. if (index !== -1) {
  55996. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55997. }
  55998. };
  55999. // end of sub system methods
  56000. ParticleSystem.prototype._update = function (newParticles) {
  56001. // Update current
  56002. this._alive = this._particles.length > 0;
  56003. this.updateFunction(this._particles);
  56004. // Add new ones
  56005. var worldMatrix;
  56006. if (this.emitter.position) {
  56007. var emitterMesh = this.emitter;
  56008. worldMatrix = emitterMesh.getWorldMatrix();
  56009. }
  56010. else {
  56011. var emitterPosition = this.emitter;
  56012. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56013. }
  56014. var particle;
  56015. for (var index = 0; index < newParticles; index++) {
  56016. if (this._particles.length === this._capacity) {
  56017. break;
  56018. }
  56019. particle = this._createParticle();
  56020. this._particles.push(particle);
  56021. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56022. if (this.startPositionFunction) {
  56023. this.startPositionFunction(worldMatrix, particle.position, particle);
  56024. }
  56025. else {
  56026. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56027. }
  56028. if (this.startDirectionFunction) {
  56029. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56030. }
  56031. else {
  56032. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56033. }
  56034. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56035. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56036. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56037. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56038. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56039. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56040. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56041. }
  56042. };
  56043. ParticleSystem.prototype._getEffect = function () {
  56044. if (this._customEffect) {
  56045. return this._customEffect;
  56046. }
  56047. ;
  56048. var defines = [];
  56049. if (this._scene.clipPlane) {
  56050. defines.push("#define CLIPPLANE");
  56051. }
  56052. if (this._isAnimationSheetEnabled) {
  56053. defines.push("#define ANIMATESHEET");
  56054. }
  56055. // Effect
  56056. var join = defines.join("\n");
  56057. if (this._cachedDefines !== join) {
  56058. this._cachedDefines = join;
  56059. var attributesNamesOrOptions;
  56060. var effectCreationOption;
  56061. if (this._isAnimationSheetEnabled) {
  56062. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56063. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56064. }
  56065. else {
  56066. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56067. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56068. }
  56069. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56070. }
  56071. return this._effect;
  56072. };
  56073. /**
  56074. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56075. */
  56076. ParticleSystem.prototype.animate = function () {
  56077. if (!this._started)
  56078. return;
  56079. var effect = this._getEffect();
  56080. // Check
  56081. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56082. return;
  56083. if (this._currentRenderId === this._scene.getRenderId()) {
  56084. return;
  56085. }
  56086. this._currentRenderId = this._scene.getRenderId();
  56087. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56088. // determine the number of particles we need to create
  56089. var newParticles;
  56090. if (this.manualEmitCount > -1) {
  56091. newParticles = this.manualEmitCount;
  56092. this._newPartsExcess = 0;
  56093. this.manualEmitCount = 0;
  56094. }
  56095. else {
  56096. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56097. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56098. }
  56099. if (this._newPartsExcess > 1.0) {
  56100. newParticles += this._newPartsExcess >> 0;
  56101. this._newPartsExcess -= this._newPartsExcess >> 0;
  56102. }
  56103. this._alive = false;
  56104. if (!this._stopped) {
  56105. this._actualFrame += this._scaledUpdateSpeed;
  56106. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56107. this.stop();
  56108. }
  56109. else {
  56110. newParticles = 0;
  56111. }
  56112. this._update(newParticles);
  56113. // Stopped?
  56114. if (this._stopped) {
  56115. if (!this._alive) {
  56116. this._started = false;
  56117. if (this.onAnimationEnd) {
  56118. this.onAnimationEnd();
  56119. }
  56120. if (this.disposeOnStop) {
  56121. this._scene._toBeDisposed.push(this);
  56122. }
  56123. }
  56124. }
  56125. // Animation sheet
  56126. if (this._isAnimationSheetEnabled) {
  56127. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56128. }
  56129. else {
  56130. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56131. }
  56132. // Update VBO
  56133. var offset = 0;
  56134. for (var index = 0; index < this._particles.length; index++) {
  56135. var particle = this._particles[index];
  56136. this._appendParticleVertexes(offset, particle);
  56137. offset += 4;
  56138. }
  56139. if (this._vertexBuffer) {
  56140. this._vertexBuffer.update(this._vertexData);
  56141. }
  56142. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56143. this.stop();
  56144. }
  56145. };
  56146. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56147. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56148. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56149. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56150. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56151. };
  56152. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56153. this._appendParticleVertex(offset++, particle, 0, 0);
  56154. this._appendParticleVertex(offset++, particle, 1, 0);
  56155. this._appendParticleVertex(offset++, particle, 1, 1);
  56156. this._appendParticleVertex(offset++, particle, 0, 1);
  56157. };
  56158. /**
  56159. * Rebuilds the particle system.
  56160. */
  56161. ParticleSystem.prototype.rebuild = function () {
  56162. this._createIndexBuffer();
  56163. if (this._vertexBuffer) {
  56164. this._vertexBuffer._rebuild();
  56165. }
  56166. };
  56167. /**
  56168. * Is this system ready to be used/rendered
  56169. * @return true if the system is ready
  56170. */
  56171. ParticleSystem.prototype.isReady = function () {
  56172. var effect = this._getEffect();
  56173. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56174. return false;
  56175. }
  56176. return true;
  56177. };
  56178. /**
  56179. * Renders the particle system in its current state.
  56180. * @returns the current number of particles
  56181. */
  56182. ParticleSystem.prototype.render = function () {
  56183. var effect = this._getEffect();
  56184. // Check
  56185. if (!this.isReady() || !this._particles.length) {
  56186. return 0;
  56187. }
  56188. var engine = this._scene.getEngine();
  56189. // Render
  56190. engine.enableEffect(effect);
  56191. engine.setState(false);
  56192. var viewMatrix = this._scene.getViewMatrix();
  56193. effect.setTexture("diffuseSampler", this.particleTexture);
  56194. effect.setMatrix("view", viewMatrix);
  56195. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56196. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56197. var baseSize = this.particleTexture.getBaseSize();
  56198. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56199. }
  56200. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56201. if (this._scene.clipPlane) {
  56202. var clipPlane = this._scene.clipPlane;
  56203. var invView = viewMatrix.clone();
  56204. invView.invert();
  56205. effect.setMatrix("invView", invView);
  56206. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56207. }
  56208. // VBOs
  56209. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56210. // Draw order
  56211. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56212. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56213. }
  56214. else {
  56215. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56216. }
  56217. if (this.forceDepthWrite) {
  56218. engine.setDepthWrite(true);
  56219. }
  56220. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56221. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56222. return this._particles.length;
  56223. };
  56224. /**
  56225. * Disposes the particle system and free the associated resources
  56226. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56227. */
  56228. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56229. if (disposeTexture === void 0) { disposeTexture = true; }
  56230. if (this._vertexBuffer) {
  56231. this._vertexBuffer.dispose();
  56232. this._vertexBuffer = null;
  56233. }
  56234. if (this._indexBuffer) {
  56235. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56236. this._indexBuffer = null;
  56237. }
  56238. if (disposeTexture && this.particleTexture) {
  56239. this.particleTexture.dispose();
  56240. this.particleTexture = null;
  56241. }
  56242. this._removeFromRoot();
  56243. // Remove from scene
  56244. var index = this._scene.particleSystems.indexOf(this);
  56245. if (index > -1) {
  56246. this._scene.particleSystems.splice(index, 1);
  56247. }
  56248. // Callback
  56249. this.onDisposeObservable.notifyObservers(this);
  56250. this.onDisposeObservable.clear();
  56251. };
  56252. /**
  56253. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56254. * @param radius The radius of the sphere to emit from
  56255. * @returns the emitter
  56256. */
  56257. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56258. if (radius === void 0) { radius = 1; }
  56259. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56260. this.particleEmitterType = particleEmitter;
  56261. return particleEmitter;
  56262. };
  56263. /**
  56264. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56265. * @param radius The radius of the sphere to emit from
  56266. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56267. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56268. * @returns the emitter
  56269. */
  56270. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56271. if (radius === void 0) { radius = 1; }
  56272. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56273. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56274. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56275. this.particleEmitterType = particleEmitter;
  56276. return particleEmitter;
  56277. };
  56278. /**
  56279. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56280. * @param radius The radius of the cone to emit from
  56281. * @param angle The base angle of the cone
  56282. * @returns the emitter
  56283. */
  56284. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56285. if (radius === void 0) { radius = 1; }
  56286. if (angle === void 0) { angle = Math.PI / 4; }
  56287. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56288. this.particleEmitterType = particleEmitter;
  56289. return particleEmitter;
  56290. };
  56291. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56292. /**
  56293. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56294. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56295. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56296. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56297. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56298. * @returns the emitter
  56299. */
  56300. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56301. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56302. this.particleEmitterType = particleEmitter;
  56303. this.direction1 = direction1;
  56304. this.direction2 = direction2;
  56305. this.minEmitBox = minEmitBox;
  56306. this.maxEmitBox = maxEmitBox;
  56307. return particleEmitter;
  56308. };
  56309. // Clone
  56310. /**
  56311. * Clones the particle system.
  56312. * @param name The name of the cloned object
  56313. * @param newEmitter The new emitter to use
  56314. * @returns the cloned particle system
  56315. */
  56316. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56317. var custom = null;
  56318. var program = null;
  56319. if (this.customShader != null) {
  56320. program = this.customShader;
  56321. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56322. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56323. }
  56324. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56325. result.customShader = program;
  56326. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56327. if (newEmitter === undefined) {
  56328. newEmitter = this.emitter;
  56329. }
  56330. result.emitter = newEmitter;
  56331. if (this.particleTexture) {
  56332. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56333. }
  56334. if (!this.preventAutoStart) {
  56335. result.start();
  56336. }
  56337. return result;
  56338. };
  56339. /**
  56340. * Serializes the particle system to a JSON object.
  56341. * @returns the JSON object
  56342. */
  56343. ParticleSystem.prototype.serialize = function () {
  56344. var serializationObject = {};
  56345. serializationObject.name = this.name;
  56346. serializationObject.id = this.id;
  56347. // Emitter
  56348. if (this.emitter.position) {
  56349. var emitterMesh = this.emitter;
  56350. serializationObject.emitterId = emitterMesh.id;
  56351. }
  56352. else {
  56353. var emitterPosition = this.emitter;
  56354. serializationObject.emitter = emitterPosition.asArray();
  56355. }
  56356. serializationObject.capacity = this.getCapacity();
  56357. if (this.particleTexture) {
  56358. serializationObject.textureName = this.particleTexture.name;
  56359. }
  56360. // Animations
  56361. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56362. // Particle system
  56363. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56364. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56365. serializationObject.minSize = this.minSize;
  56366. serializationObject.maxSize = this.maxSize;
  56367. serializationObject.minEmitPower = this.minEmitPower;
  56368. serializationObject.maxEmitPower = this.maxEmitPower;
  56369. serializationObject.minLifeTime = this.minLifeTime;
  56370. serializationObject.maxLifeTime = this.maxLifeTime;
  56371. serializationObject.emitRate = this.emitRate;
  56372. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56373. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56374. serializationObject.gravity = this.gravity.asArray();
  56375. serializationObject.direction1 = this.direction1.asArray();
  56376. serializationObject.direction2 = this.direction2.asArray();
  56377. serializationObject.color1 = this.color1.asArray();
  56378. serializationObject.color2 = this.color2.asArray();
  56379. serializationObject.colorDead = this.colorDead.asArray();
  56380. serializationObject.updateSpeed = this.updateSpeed;
  56381. serializationObject.targetStopDuration = this.targetStopDuration;
  56382. serializationObject.textureMask = this.textureMask.asArray();
  56383. serializationObject.blendMode = this.blendMode;
  56384. serializationObject.customShader = this.customShader;
  56385. serializationObject.preventAutoStart = this.preventAutoStart;
  56386. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56387. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56388. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56389. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56390. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56391. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56392. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56393. // Emitter
  56394. if (this.particleEmitterType) {
  56395. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56396. }
  56397. return serializationObject;
  56398. };
  56399. /**
  56400. * Parses a JSON object to create a particle system.
  56401. * @param parsedParticleSystem The JSON object to parse
  56402. * @param scene The scene to create the particle system in
  56403. * @param rootUrl The root url to use to load external dependencies like texture
  56404. * @returns the Parsed particle system
  56405. */
  56406. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56407. var name = parsedParticleSystem.name;
  56408. var custom = null;
  56409. var program = null;
  56410. if (parsedParticleSystem.customShader) {
  56411. program = parsedParticleSystem.customShader;
  56412. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56413. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56414. }
  56415. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56416. particleSystem.customShader = program;
  56417. if (parsedParticleSystem.id) {
  56418. particleSystem.id = parsedParticleSystem.id;
  56419. }
  56420. // Auto start
  56421. if (parsedParticleSystem.preventAutoStart) {
  56422. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56423. }
  56424. // Texture
  56425. if (parsedParticleSystem.textureName) {
  56426. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56427. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56428. }
  56429. // Emitter
  56430. if (parsedParticleSystem.emitterId) {
  56431. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56432. }
  56433. else {
  56434. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56435. }
  56436. // Animations
  56437. if (parsedParticleSystem.animations) {
  56438. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56439. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56440. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56441. }
  56442. }
  56443. if (parsedParticleSystem.autoAnimate) {
  56444. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56445. }
  56446. // Particle system
  56447. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56448. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56449. particleSystem.minSize = parsedParticleSystem.minSize;
  56450. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56451. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56452. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56453. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56454. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56455. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56456. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56457. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56458. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56459. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56460. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56461. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56462. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56463. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56464. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56465. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56466. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56467. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56468. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56469. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56470. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56471. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56472. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56473. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56474. if (!particleSystem.preventAutoStart) {
  56475. particleSystem.start();
  56476. }
  56477. return particleSystem;
  56478. };
  56479. /**
  56480. * Source color is added to the destination color without alpha affecting the result.
  56481. */
  56482. ParticleSystem.BLENDMODE_ONEONE = 0;
  56483. /**
  56484. * Blend current color and particle color using particle’s alpha.
  56485. */
  56486. ParticleSystem.BLENDMODE_STANDARD = 1;
  56487. return ParticleSystem;
  56488. }());
  56489. BABYLON.ParticleSystem = ParticleSystem;
  56490. })(BABYLON || (BABYLON = {}));
  56491. //# sourceMappingURL=babylon.particleSystem.js.map
  56492. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56493. var BABYLON;
  56494. (function (BABYLON) {
  56495. /**
  56496. * Particle emitter emitting particles from the inside of a box.
  56497. * It emits the particles randomly between 2 given directions.
  56498. */
  56499. var BoxParticleEmitter = /** @class */ (function () {
  56500. /**
  56501. * Creates a new instance BoxParticleEmitter
  56502. */
  56503. function BoxParticleEmitter() {
  56504. /**
  56505. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56506. */
  56507. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56508. /**
  56509. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56510. */
  56511. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56512. /**
  56513. * 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.
  56514. */
  56515. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56516. /**
  56517. * 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.
  56518. */
  56519. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56520. }
  56521. /**
  56522. * Called by the particle System when the direction is computed for the created particle.
  56523. * @param emitPower is the power of the particle (speed)
  56524. * @param worldMatrix is the world matrix of the particle system
  56525. * @param directionToUpdate is the direction vector to update with the result
  56526. * @param particle is the particle we are computed the direction for
  56527. */
  56528. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56529. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56530. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56531. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56532. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56533. };
  56534. /**
  56535. * Called by the particle System when the position is computed for the created particle.
  56536. * @param worldMatrix is the world matrix of the particle system
  56537. * @param positionToUpdate is the position vector to update with the result
  56538. * @param particle is the particle we are computed the position for
  56539. */
  56540. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56541. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56542. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56543. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56544. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56545. };
  56546. /**
  56547. * Clones the current emitter and returns a copy of it
  56548. * @returns the new emitter
  56549. */
  56550. BoxParticleEmitter.prototype.clone = function () {
  56551. var newOne = new BoxParticleEmitter();
  56552. BABYLON.Tools.DeepCopy(this, newOne);
  56553. return newOne;
  56554. };
  56555. /**
  56556. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56557. * @param effect defines the update shader
  56558. */
  56559. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56560. effect.setVector3("direction1", this.direction1);
  56561. effect.setVector3("direction2", this.direction2);
  56562. effect.setVector3("minEmitBox", this.minEmitBox);
  56563. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56564. };
  56565. /**
  56566. * Returns a string to use to update the GPU particles update shader
  56567. * @returns a string containng the defines string
  56568. */
  56569. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56570. return "#define BOXEMITTER";
  56571. };
  56572. /**
  56573. * Returns the string "BoxEmitter"
  56574. * @returns a string containing the class name
  56575. */
  56576. BoxParticleEmitter.prototype.getClassName = function () {
  56577. return "BoxEmitter";
  56578. };
  56579. /**
  56580. * Serializes the particle system to a JSON object.
  56581. * @returns the JSON object
  56582. */
  56583. BoxParticleEmitter.prototype.serialize = function () {
  56584. var serializationObject = {};
  56585. serializationObject.type = this.getClassName();
  56586. serializationObject.direction1 = this.direction1.asArray();
  56587. ;
  56588. serializationObject.direction2 = this.direction2.asArray();
  56589. ;
  56590. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56591. ;
  56592. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56593. ;
  56594. return serializationObject;
  56595. };
  56596. /**
  56597. * Parse properties from a JSON object
  56598. * @param serializationObject defines the JSON object
  56599. */
  56600. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56601. this.direction1.copyFrom(serializationObject.direction1);
  56602. this.direction2.copyFrom(serializationObject.direction2);
  56603. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56604. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56605. };
  56606. return BoxParticleEmitter;
  56607. }());
  56608. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56609. })(BABYLON || (BABYLON = {}));
  56610. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56611. var BABYLON;
  56612. (function (BABYLON) {
  56613. /**
  56614. * Particle emitter emitting particles from the inside of a cone.
  56615. * It emits the particles alongside the cone volume from the base to the particle.
  56616. * The emission direction might be randomized.
  56617. */
  56618. var ConeParticleEmitter = /** @class */ (function () {
  56619. /**
  56620. * Creates a new instance ConeParticleEmitter
  56621. * @param radius the radius of the emission cone (1 by default)
  56622. * @param angles the cone base angle (PI by default)
  56623. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56624. */
  56625. function ConeParticleEmitter(radius,
  56626. /**
  56627. * The radius of the emission cone.
  56628. */
  56629. angle,
  56630. /**
  56631. * The cone base angle.
  56632. */
  56633. directionRandomizer) {
  56634. if (radius === void 0) { radius = 1; }
  56635. if (angle === void 0) { angle = Math.PI; }
  56636. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56637. this.angle = angle;
  56638. this.directionRandomizer = directionRandomizer;
  56639. this.radius = radius;
  56640. }
  56641. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56642. /**
  56643. * Gets the radius of the emission cone.
  56644. */
  56645. get: function () {
  56646. return this._radius;
  56647. },
  56648. /**
  56649. * Sets the radius of the emission cone.
  56650. */
  56651. set: function (value) {
  56652. this._radius = value;
  56653. if (this.angle !== 0) {
  56654. this._height = value / Math.tan(this.angle / 2);
  56655. }
  56656. else {
  56657. this._height = 1;
  56658. }
  56659. },
  56660. enumerable: true,
  56661. configurable: true
  56662. });
  56663. /**
  56664. * Called by the particle System when the direction is computed for the created particle.
  56665. * @param emitPower is the power of the particle (speed)
  56666. * @param worldMatrix is the world matrix of the particle system
  56667. * @param directionToUpdate is the direction vector to update with the result
  56668. * @param particle is the particle we are computed the direction for
  56669. */
  56670. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56671. if (this.angle === 0) {
  56672. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56673. }
  56674. else {
  56675. // measure the direction Vector from the emitter to the particle.
  56676. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56677. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56678. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56679. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56680. direction.x += randX;
  56681. direction.y += randY;
  56682. direction.z += randZ;
  56683. direction.normalize();
  56684. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56685. }
  56686. };
  56687. /**
  56688. * Called by the particle System when the position is computed for the created particle.
  56689. * @param worldMatrix is the world matrix of the particle system
  56690. * @param positionToUpdate is the position vector to update with the result
  56691. * @param particle is the particle we are computed the position for
  56692. */
  56693. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56694. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56695. var h = BABYLON.Scalar.RandomRange(0, 1);
  56696. // Better distribution in a cone at normal angles.
  56697. h = 1 - h * h;
  56698. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56699. radius = radius * h;
  56700. var randX = radius * Math.sin(s);
  56701. var randZ = radius * Math.cos(s);
  56702. var randY = h * this._height;
  56703. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56704. };
  56705. /**
  56706. * Clones the current emitter and returns a copy of it
  56707. * @returns the new emitter
  56708. */
  56709. ConeParticleEmitter.prototype.clone = function () {
  56710. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56711. BABYLON.Tools.DeepCopy(this, newOne);
  56712. return newOne;
  56713. };
  56714. /**
  56715. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56716. * @param effect defines the update shader
  56717. */
  56718. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56719. effect.setFloat("radius", this.radius);
  56720. effect.setFloat("angle", this.angle);
  56721. effect.setFloat("height", this._height);
  56722. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56723. };
  56724. /**
  56725. * Returns a string to use to update the GPU particles update shader
  56726. * @returns a string containng the defines string
  56727. */
  56728. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56729. return "#define CONEEMITTER";
  56730. };
  56731. /**
  56732. * Returns the string "BoxEmitter"
  56733. * @returns a string containing the class name
  56734. */
  56735. ConeParticleEmitter.prototype.getClassName = function () {
  56736. return "ConeEmitter";
  56737. };
  56738. /**
  56739. * Serializes the particle system to a JSON object.
  56740. * @returns the JSON object
  56741. */
  56742. ConeParticleEmitter.prototype.serialize = function () {
  56743. var serializationObject = {};
  56744. serializationObject.type = this.getClassName();
  56745. serializationObject.radius = this.radius;
  56746. serializationObject.angle = this.angle;
  56747. serializationObject.directionRandomizer = this.directionRandomizer;
  56748. return serializationObject;
  56749. };
  56750. /**
  56751. * Parse properties from a JSON object
  56752. * @param serializationObject defines the JSON object
  56753. */
  56754. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56755. this.radius = serializationObject.radius;
  56756. this.angle = serializationObject.angle;
  56757. this.directionRandomizer = serializationObject.directionRandomizer;
  56758. };
  56759. return ConeParticleEmitter;
  56760. }());
  56761. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56762. })(BABYLON || (BABYLON = {}));
  56763. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56764. var BABYLON;
  56765. (function (BABYLON) {
  56766. /**
  56767. * Particle emitter emitting particles from the inside of a sphere.
  56768. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56769. */
  56770. var SphereParticleEmitter = /** @class */ (function () {
  56771. /**
  56772. * Creates a new instance SphereParticleEmitter
  56773. * @param radius the radius of the emission sphere (1 by default)
  56774. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56775. */
  56776. function SphereParticleEmitter(
  56777. /**
  56778. * The radius of the emission sphere.
  56779. */
  56780. radius,
  56781. /**
  56782. * How much to randomize the particle direction [0-1].
  56783. */
  56784. directionRandomizer) {
  56785. if (radius === void 0) { radius = 1; }
  56786. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56787. this.radius = radius;
  56788. this.directionRandomizer = directionRandomizer;
  56789. }
  56790. /**
  56791. * Called by the particle System when the direction is computed for the created particle.
  56792. * @param emitPower is the power of the particle (speed)
  56793. * @param worldMatrix is the world matrix of the particle system
  56794. * @param directionToUpdate is the direction vector to update with the result
  56795. * @param particle is the particle we are computed the direction for
  56796. */
  56797. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56798. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56799. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56800. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56801. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56802. direction.x += randX;
  56803. direction.y += randY;
  56804. direction.z += randZ;
  56805. direction.normalize();
  56806. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56807. };
  56808. /**
  56809. * Called by the particle System when the position is computed for the created particle.
  56810. * @param worldMatrix is the world matrix of the particle system
  56811. * @param positionToUpdate is the position vector to update with the result
  56812. * @param particle is the particle we are computed the position for
  56813. */
  56814. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56815. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56816. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56817. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56818. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56819. var randY = randRadius * Math.cos(theta);
  56820. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56821. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56822. };
  56823. /**
  56824. * Clones the current emitter and returns a copy of it
  56825. * @returns the new emitter
  56826. */
  56827. SphereParticleEmitter.prototype.clone = function () {
  56828. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56829. BABYLON.Tools.DeepCopy(this, newOne);
  56830. return newOne;
  56831. };
  56832. /**
  56833. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56834. * @param effect defines the update shader
  56835. */
  56836. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56837. effect.setFloat("radius", this.radius);
  56838. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56839. };
  56840. /**
  56841. * Returns a string to use to update the GPU particles update shader
  56842. * @returns a string containng the defines string
  56843. */
  56844. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56845. return "#define SPHEREEMITTER";
  56846. };
  56847. /**
  56848. * Returns the string "SphereParticleEmitter"
  56849. * @returns a string containing the class name
  56850. */
  56851. SphereParticleEmitter.prototype.getClassName = function () {
  56852. return "SphereParticleEmitter";
  56853. };
  56854. /**
  56855. * Serializes the particle system to a JSON object.
  56856. * @returns the JSON object
  56857. */
  56858. SphereParticleEmitter.prototype.serialize = function () {
  56859. var serializationObject = {};
  56860. serializationObject.type = this.getClassName();
  56861. serializationObject.radius = this.radius;
  56862. serializationObject.directionRandomizer = this.directionRandomizer;
  56863. return serializationObject;
  56864. };
  56865. /**
  56866. * Parse properties from a JSON object
  56867. * @param serializationObject defines the JSON object
  56868. */
  56869. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56870. this.radius = serializationObject.radius;
  56871. this.directionRandomizer = serializationObject.directionRandomizer;
  56872. };
  56873. return SphereParticleEmitter;
  56874. }());
  56875. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56876. /**
  56877. * Particle emitter emitting particles from the inside of a sphere.
  56878. * It emits the particles randomly between two vectors.
  56879. */
  56880. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56881. __extends(SphereDirectedParticleEmitter, _super);
  56882. /**
  56883. * Creates a new instance SphereDirectedParticleEmitter
  56884. * @param radius the radius of the emission sphere (1 by default)
  56885. * @param direction1 the min limit of the emission direction (up vector by default)
  56886. * @param direction2 the max limit of the emission direction (up vector by default)
  56887. */
  56888. function SphereDirectedParticleEmitter(radius,
  56889. /**
  56890. * The min limit of the emission direction.
  56891. */
  56892. direction1,
  56893. /**
  56894. * The max limit of the emission direction.
  56895. */
  56896. direction2) {
  56897. if (radius === void 0) { radius = 1; }
  56898. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56899. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56900. var _this = _super.call(this, radius) || this;
  56901. _this.direction1 = direction1;
  56902. _this.direction2 = direction2;
  56903. return _this;
  56904. }
  56905. /**
  56906. * Called by the particle System when the direction is computed for the created particle.
  56907. * @param emitPower is the power of the particle (speed)
  56908. * @param worldMatrix is the world matrix of the particle system
  56909. * @param directionToUpdate is the direction vector to update with the result
  56910. * @param particle is the particle we are computed the direction for
  56911. */
  56912. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56913. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56914. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56915. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56916. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56917. };
  56918. /**
  56919. * Clones the current emitter and returns a copy of it
  56920. * @returns the new emitter
  56921. */
  56922. SphereDirectedParticleEmitter.prototype.clone = function () {
  56923. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56924. BABYLON.Tools.DeepCopy(this, newOne);
  56925. return newOne;
  56926. };
  56927. /**
  56928. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56929. * @param effect defines the update shader
  56930. */
  56931. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56932. effect.setFloat("radius", this.radius);
  56933. effect.setVector3("direction1", this.direction1);
  56934. effect.setVector3("direction2", this.direction2);
  56935. };
  56936. /**
  56937. * Returns a string to use to update the GPU particles update shader
  56938. * @returns a string containng the defines string
  56939. */
  56940. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56941. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56942. };
  56943. /**
  56944. * Returns the string "SphereDirectedParticleEmitter"
  56945. * @returns a string containing the class name
  56946. */
  56947. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56948. return "SphereDirectedParticleEmitter";
  56949. };
  56950. /**
  56951. * Serializes the particle system to a JSON object.
  56952. * @returns the JSON object
  56953. */
  56954. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56955. var serializationObject = _super.prototype.serialize.call(this);
  56956. ;
  56957. serializationObject.direction1 = this.direction1.asArray();
  56958. ;
  56959. serializationObject.direction2 = this.direction2.asArray();
  56960. ;
  56961. return serializationObject;
  56962. };
  56963. /**
  56964. * Parse properties from a JSON object
  56965. * @param serializationObject defines the JSON object
  56966. */
  56967. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56968. _super.prototype.parse.call(this, serializationObject);
  56969. this.direction1.copyFrom(serializationObject.direction1);
  56970. this.direction2.copyFrom(serializationObject.direction2);
  56971. };
  56972. return SphereDirectedParticleEmitter;
  56973. }(SphereParticleEmitter));
  56974. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56975. })(BABYLON || (BABYLON = {}));
  56976. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56977. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56978. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56979. s = arguments[i];
  56980. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56981. t[p] = s[p];
  56982. }
  56983. return t;
  56984. };
  56985. var BABYLON;
  56986. (function (BABYLON) {
  56987. /**
  56988. * This represents a GPU particle system in Babylon
  56989. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56990. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56991. */
  56992. var GPUParticleSystem = /** @class */ (function () {
  56993. /**
  56994. * Instantiates a GPU particle system.
  56995. * 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.
  56996. * @param name The name of the particle system
  56997. * @param capacity The max number of particles alive at the same time
  56998. * @param scene The scene the particle system belongs to
  56999. */
  57000. function GPUParticleSystem(name, options, scene) {
  57001. /**
  57002. * The emitter represents the Mesh or position we are attaching the particle system to.
  57003. */
  57004. this.emitter = null;
  57005. /**
  57006. * The rendering group used by the Particle system to chose when to render.
  57007. */
  57008. this.renderingGroupId = 0;
  57009. /**
  57010. * The layer mask we are rendering the particles through.
  57011. */
  57012. this.layerMask = 0x0FFFFFFF;
  57013. this._targetIndex = 0;
  57014. this._currentRenderId = -1;
  57015. this._started = false;
  57016. this._stopped = false;
  57017. this._timeDelta = 0;
  57018. this._attributesStrideSize = 14;
  57019. this._actualFrame = 0;
  57020. /**
  57021. * List of animations used by the particle system.
  57022. */
  57023. this.animations = [];
  57024. /**
  57025. * An event triggered when the system is disposed.
  57026. */
  57027. this.onDisposeObservable = new BABYLON.Observable();
  57028. /**
  57029. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57030. */
  57031. this.updateSpeed = 0.01;
  57032. /**
  57033. * The amount of time the particle system is running (depends of the overall update speed).
  57034. */
  57035. this.targetStopDuration = 0;
  57036. /**
  57037. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57038. */
  57039. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57040. /**
  57041. * Minimum life time of emitting particles.
  57042. */
  57043. this.minLifeTime = 1;
  57044. /**
  57045. * Maximum life time of emitting particles.
  57046. */
  57047. this.maxLifeTime = 1;
  57048. /**
  57049. * Minimum Size of emitting particles.
  57050. */
  57051. this.minSize = 1;
  57052. /**
  57053. * Maximum Size of emitting particles.
  57054. */
  57055. this.maxSize = 1;
  57056. /**
  57057. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57058. */
  57059. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57060. /**
  57061. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57062. */
  57063. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57064. /**
  57065. * Color the particle will have at the end of its lifetime.
  57066. */
  57067. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57068. /**
  57069. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57070. */
  57071. this.emitRate = 100;
  57072. /**
  57073. * You can use gravity if you want to give an orientation to your particles.
  57074. */
  57075. this.gravity = BABYLON.Vector3.Zero();
  57076. /**
  57077. * Minimum power of emitting particles.
  57078. */
  57079. this.minEmitPower = 1;
  57080. /**
  57081. * Maximum power of emitting particles.
  57082. */
  57083. this.maxEmitPower = 1;
  57084. /**
  57085. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57086. * to override the particles.
  57087. */
  57088. this.forceDepthWrite = false;
  57089. this.id = name;
  57090. this.name = name;
  57091. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57092. this._engine = this._scene.getEngine();
  57093. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57094. this._capacity = fullOptions.capacity;
  57095. this._activeCount = fullOptions.capacity;
  57096. this._currentActiveCount = 0;
  57097. this._scene.particleSystems.push(this);
  57098. this._updateEffectOptions = {
  57099. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57100. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57101. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57102. uniformBuffersNames: [],
  57103. samplers: ["randomSampler"],
  57104. defines: "",
  57105. fallbacks: null,
  57106. onCompiled: null,
  57107. onError: null,
  57108. indexParameters: null,
  57109. maxSimultaneousLights: 0,
  57110. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57111. };
  57112. // Random data
  57113. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57114. var d = [];
  57115. for (var i = 0; i < maxTextureSize; ++i) {
  57116. d.push(Math.random());
  57117. d.push(Math.random());
  57118. d.push(Math.random());
  57119. d.push(Math.random());
  57120. }
  57121. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57122. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57123. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57124. this._randomTextureSize = maxTextureSize;
  57125. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57126. }
  57127. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57128. /**
  57129. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57130. */
  57131. get: function () {
  57132. if (!BABYLON.Engine.LastCreatedEngine) {
  57133. return false;
  57134. }
  57135. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57136. },
  57137. enumerable: true,
  57138. configurable: true
  57139. });
  57140. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57141. /**
  57142. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57143. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57144. */
  57145. get: function () {
  57146. if (this.particleEmitterType.direction1) {
  57147. return this.particleEmitterType.direction1;
  57148. }
  57149. return BABYLON.Vector3.Zero();
  57150. },
  57151. set: function (value) {
  57152. if (this.particleEmitterType.direction1) {
  57153. this.particleEmitterType.direction1 = value;
  57154. }
  57155. },
  57156. enumerable: true,
  57157. configurable: true
  57158. });
  57159. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57160. /**
  57161. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57162. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57163. */
  57164. get: function () {
  57165. if (this.particleEmitterType.direction2) {
  57166. return this.particleEmitterType.direction2;
  57167. }
  57168. return BABYLON.Vector3.Zero();
  57169. },
  57170. set: function (value) {
  57171. if (this.particleEmitterType.direction2) {
  57172. this.particleEmitterType.direction2 = value;
  57173. }
  57174. },
  57175. enumerable: true,
  57176. configurable: true
  57177. });
  57178. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57179. /**
  57180. * 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.
  57181. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57182. */
  57183. get: function () {
  57184. if (this.particleEmitterType.minEmitBox) {
  57185. return this.particleEmitterType.minEmitBox;
  57186. }
  57187. return BABYLON.Vector3.Zero();
  57188. },
  57189. set: function (value) {
  57190. if (this.particleEmitterType.minEmitBox) {
  57191. this.particleEmitterType.minEmitBox = value;
  57192. }
  57193. },
  57194. enumerable: true,
  57195. configurable: true
  57196. });
  57197. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57198. /**
  57199. * 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.
  57200. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57201. */
  57202. get: function () {
  57203. if (this.particleEmitterType.maxEmitBox) {
  57204. return this.particleEmitterType.maxEmitBox;
  57205. }
  57206. return BABYLON.Vector3.Zero();
  57207. },
  57208. set: function (value) {
  57209. if (this.particleEmitterType.maxEmitBox) {
  57210. this.particleEmitterType.maxEmitBox = value;
  57211. }
  57212. },
  57213. enumerable: true,
  57214. configurable: true
  57215. });
  57216. /**
  57217. * Gets the maximum number of particles active at the same time.
  57218. * @returns The max number of active particles.
  57219. */
  57220. GPUParticleSystem.prototype.getCapacity = function () {
  57221. return this._capacity;
  57222. };
  57223. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57224. /**
  57225. * Gets or set the number of active particles
  57226. */
  57227. get: function () {
  57228. return this._activeCount;
  57229. },
  57230. set: function (value) {
  57231. this._activeCount = Math.min(value, this._capacity);
  57232. },
  57233. enumerable: true,
  57234. configurable: true
  57235. });
  57236. /**
  57237. * Is this system ready to be used/rendered
  57238. * @return true if the system is ready
  57239. */
  57240. GPUParticleSystem.prototype.isReady = function () {
  57241. if (!this._updateEffect) {
  57242. this._recreateUpdateEffect();
  57243. this._recreateRenderEffect();
  57244. return false;
  57245. }
  57246. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57247. return false;
  57248. }
  57249. return true;
  57250. };
  57251. /**
  57252. * Gets Wether the system has been started.
  57253. * @returns True if it has been started, otherwise false.
  57254. */
  57255. GPUParticleSystem.prototype.isStarted = function () {
  57256. return this._started;
  57257. };
  57258. /**
  57259. * Starts the particle system and begins to emit.
  57260. */
  57261. GPUParticleSystem.prototype.start = function () {
  57262. this._started = true;
  57263. this._stopped = false;
  57264. };
  57265. /**
  57266. * Stops the particle system.
  57267. */
  57268. GPUParticleSystem.prototype.stop = function () {
  57269. this._stopped = true;
  57270. };
  57271. /**
  57272. * Remove all active particles
  57273. */
  57274. GPUParticleSystem.prototype.reset = function () {
  57275. this._releaseBuffers();
  57276. this._releaseVAOs();
  57277. this._currentActiveCount = 0;
  57278. this._targetIndex = 0;
  57279. };
  57280. /**
  57281. * Returns the string "GPUParticleSystem"
  57282. * @returns a string containing the class name
  57283. */
  57284. GPUParticleSystem.prototype.getClassName = function () {
  57285. return "GPUParticleSystem";
  57286. };
  57287. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57288. var updateVertexBuffers = {};
  57289. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57290. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57291. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57292. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57293. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57294. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57295. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57296. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57297. this._engine.bindArrayBuffer(null);
  57298. return vao;
  57299. };
  57300. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57301. var renderVertexBuffers = {};
  57302. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57303. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57304. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57305. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57306. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57307. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57308. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57309. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57310. this._engine.bindArrayBuffer(null);
  57311. return vao;
  57312. };
  57313. GPUParticleSystem.prototype._initialize = function (force) {
  57314. if (force === void 0) { force = false; }
  57315. if (this._buffer0 && !force) {
  57316. return;
  57317. }
  57318. var engine = this._scene.getEngine();
  57319. var data = new Array();
  57320. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57321. // position
  57322. data.push(0.0);
  57323. data.push(0.0);
  57324. data.push(0.0);
  57325. // Age and life
  57326. data.push(0.0); // create the particle as a dead one to create a new one at start
  57327. data.push(0.0);
  57328. // Seed
  57329. data.push(Math.random());
  57330. // Size
  57331. data.push(0.0);
  57332. // color
  57333. data.push(0.0);
  57334. data.push(0.0);
  57335. data.push(0.0);
  57336. data.push(0.0);
  57337. // direction
  57338. data.push(0.0);
  57339. data.push(0.0);
  57340. data.push(0.0);
  57341. }
  57342. // Sprite data
  57343. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57344. -0.5, 0.5, 0, 1,
  57345. -0.5, -0.5, 0, 0,
  57346. 0.5, -0.5, 1, 0]);
  57347. // Buffers
  57348. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57349. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57350. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57351. // Update VAO
  57352. this._updateVAO = [];
  57353. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57354. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57355. // Render VAO
  57356. this._renderVAO = [];
  57357. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57358. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57359. // Links
  57360. this._sourceBuffer = this._buffer0;
  57361. this._targetBuffer = this._buffer1;
  57362. };
  57363. /** @hidden */
  57364. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57365. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57366. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57367. return;
  57368. }
  57369. this._updateEffectOptions.defines = defines;
  57370. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57371. };
  57372. /** @hidden */
  57373. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57374. var defines = "";
  57375. if (this._scene.clipPlane) {
  57376. defines = "\n#define CLIPPLANE";
  57377. }
  57378. if (this._renderEffect && this._renderEffect.defines === defines) {
  57379. return;
  57380. }
  57381. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57382. };
  57383. /**
  57384. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57385. */
  57386. GPUParticleSystem.prototype.animate = function () {
  57387. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57388. this._actualFrame += this._timeDelta;
  57389. if (!this._stopped) {
  57390. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57391. this.stop();
  57392. }
  57393. }
  57394. };
  57395. /**
  57396. * Renders the particle system in its current state.
  57397. * @returns the current number of particles
  57398. */
  57399. GPUParticleSystem.prototype.render = function () {
  57400. if (!this._started) {
  57401. return 0;
  57402. }
  57403. this._recreateUpdateEffect();
  57404. this._recreateRenderEffect();
  57405. if (!this.isReady()) {
  57406. return 0;
  57407. }
  57408. if (this._currentRenderId === this._scene.getRenderId()) {
  57409. return 0;
  57410. }
  57411. this._currentRenderId = this._scene.getRenderId();
  57412. // Get everything ready to render
  57413. this._initialize();
  57414. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57415. // Enable update effect
  57416. this._engine.enableEffect(this._updateEffect);
  57417. this._engine.setState(false);
  57418. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57419. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57420. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57421. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57422. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57423. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57424. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57425. this._updateEffect.setDirectColor4("color1", this.color1);
  57426. this._updateEffect.setDirectColor4("color2", this.color2);
  57427. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57428. this._updateEffect.setVector3("gravity", this.gravity);
  57429. if (this.particleEmitterType) {
  57430. this.particleEmitterType.applyToShader(this._updateEffect);
  57431. }
  57432. var emitterWM;
  57433. if (this.emitter.position) {
  57434. var emitterMesh = this.emitter;
  57435. emitterWM = emitterMesh.getWorldMatrix();
  57436. }
  57437. else {
  57438. var emitterPosition = this.emitter;
  57439. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57440. }
  57441. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57442. // Bind source VAO
  57443. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57444. // Update
  57445. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57446. this._engine.setRasterizerState(false);
  57447. this._engine.beginTransformFeedback();
  57448. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57449. this._engine.endTransformFeedback();
  57450. this._engine.setRasterizerState(true);
  57451. this._engine.bindTransformFeedbackBuffer(null);
  57452. // Enable render effect
  57453. this._engine.enableEffect(this._renderEffect);
  57454. var viewMatrix = this._scene.getViewMatrix();
  57455. this._renderEffect.setMatrix("view", viewMatrix);
  57456. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57457. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57458. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57459. if (this._scene.clipPlane) {
  57460. var clipPlane = this._scene.clipPlane;
  57461. var invView = viewMatrix.clone();
  57462. invView.invert();
  57463. this._renderEffect.setMatrix("invView", invView);
  57464. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57465. }
  57466. // Draw order
  57467. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57468. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57469. }
  57470. else {
  57471. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57472. }
  57473. if (this.forceDepthWrite) {
  57474. this._engine.setDepthWrite(true);
  57475. }
  57476. // Bind source VAO
  57477. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57478. // Render
  57479. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57480. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57481. // Switch VAOs
  57482. this._targetIndex++;
  57483. if (this._targetIndex === 2) {
  57484. this._targetIndex = 0;
  57485. }
  57486. // Switch buffers
  57487. var tmpBuffer = this._sourceBuffer;
  57488. this._sourceBuffer = this._targetBuffer;
  57489. this._targetBuffer = tmpBuffer;
  57490. return this._currentActiveCount;
  57491. };
  57492. /**
  57493. * Rebuilds the particle system
  57494. */
  57495. GPUParticleSystem.prototype.rebuild = function () {
  57496. this._initialize(true);
  57497. };
  57498. GPUParticleSystem.prototype._releaseBuffers = function () {
  57499. if (this._buffer0) {
  57500. this._buffer0.dispose();
  57501. this._buffer0 = null;
  57502. }
  57503. if (this._buffer1) {
  57504. this._buffer1.dispose();
  57505. this._buffer1 = null;
  57506. }
  57507. if (this._spriteBuffer) {
  57508. this._spriteBuffer.dispose();
  57509. this._spriteBuffer = null;
  57510. }
  57511. };
  57512. GPUParticleSystem.prototype._releaseVAOs = function () {
  57513. if (!this._updateVAO) {
  57514. return;
  57515. }
  57516. for (var index = 0; index < this._updateVAO.length; index++) {
  57517. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57518. }
  57519. this._updateVAO = [];
  57520. for (var index = 0; index < this._renderVAO.length; index++) {
  57521. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57522. }
  57523. this._renderVAO = [];
  57524. };
  57525. /**
  57526. * Disposes the particle system and free the associated resources
  57527. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57528. */
  57529. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57530. if (disposeTexture === void 0) { disposeTexture = true; }
  57531. var index = this._scene.particleSystems.indexOf(this);
  57532. if (index > -1) {
  57533. this._scene.particleSystems.splice(index, 1);
  57534. }
  57535. this._releaseBuffers();
  57536. this._releaseVAOs();
  57537. if (this._randomTexture) {
  57538. this._randomTexture.dispose();
  57539. this._randomTexture = null;
  57540. }
  57541. if (disposeTexture && this.particleTexture) {
  57542. this.particleTexture.dispose();
  57543. this.particleTexture = null;
  57544. }
  57545. // Callback
  57546. this.onDisposeObservable.notifyObservers(this);
  57547. this.onDisposeObservable.clear();
  57548. };
  57549. /**
  57550. * Clones the particle system.
  57551. * @param name The name of the cloned object
  57552. * @param newEmitter The new emitter to use
  57553. * @returns the cloned particle system
  57554. */
  57555. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57556. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57557. BABYLON.Tools.DeepCopy(this, result);
  57558. if (newEmitter === undefined) {
  57559. newEmitter = this.emitter;
  57560. }
  57561. result.emitter = newEmitter;
  57562. if (this.particleTexture) {
  57563. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57564. }
  57565. return result;
  57566. };
  57567. /**
  57568. * Serializes the particle system to a JSON object.
  57569. * @returns the JSON object
  57570. */
  57571. GPUParticleSystem.prototype.serialize = function () {
  57572. var serializationObject = {};
  57573. serializationObject.name = this.name;
  57574. serializationObject.id = this.id;
  57575. // Emitter
  57576. if (this.emitter.position) {
  57577. var emitterMesh = this.emitter;
  57578. serializationObject.emitterId = emitterMesh.id;
  57579. }
  57580. else {
  57581. var emitterPosition = this.emitter;
  57582. serializationObject.emitter = emitterPosition.asArray();
  57583. }
  57584. serializationObject.capacity = this.getCapacity();
  57585. if (this.particleTexture) {
  57586. serializationObject.textureName = this.particleTexture.name;
  57587. }
  57588. // Animations
  57589. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57590. // Particle system
  57591. serializationObject.activeParticleCount = this.activeParticleCount;
  57592. serializationObject.randomTextureSize = this._randomTextureSize;
  57593. serializationObject.minSize = this.minSize;
  57594. serializationObject.maxSize = this.maxSize;
  57595. serializationObject.minEmitPower = this.minEmitPower;
  57596. serializationObject.maxEmitPower = this.maxEmitPower;
  57597. serializationObject.minLifeTime = this.minLifeTime;
  57598. serializationObject.maxLifeTime = this.maxLifeTime;
  57599. serializationObject.emitRate = this.emitRate;
  57600. serializationObject.gravity = this.gravity.asArray();
  57601. serializationObject.color1 = this.color1.asArray();
  57602. serializationObject.color2 = this.color2.asArray();
  57603. serializationObject.colorDead = this.colorDead.asArray();
  57604. serializationObject.updateSpeed = this.updateSpeed;
  57605. serializationObject.targetStopDuration = this.targetStopDuration;
  57606. serializationObject.blendMode = this.blendMode;
  57607. // Emitter
  57608. if (this.particleEmitterType) {
  57609. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57610. }
  57611. return serializationObject;
  57612. };
  57613. /**
  57614. * Parses a JSON object to create a GPU particle system.
  57615. * @param parsedParticleSystem The JSON object to parse
  57616. * @param scene The scene to create the particle system in
  57617. * @param rootUrl The root url to use to load external dependencies like texture
  57618. * @returns the parsed GPU particle system
  57619. */
  57620. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57621. var name = parsedParticleSystem.name;
  57622. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57623. if (parsedParticleSystem.id) {
  57624. particleSystem.id = parsedParticleSystem.id;
  57625. }
  57626. // Texture
  57627. if (parsedParticleSystem.textureName) {
  57628. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57629. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57630. }
  57631. // Emitter
  57632. if (parsedParticleSystem.emitterId) {
  57633. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57634. }
  57635. else {
  57636. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57637. }
  57638. // Animations
  57639. if (parsedParticleSystem.animations) {
  57640. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57641. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57642. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57643. }
  57644. }
  57645. // Particle system
  57646. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57647. particleSystem.minSize = parsedParticleSystem.minSize;
  57648. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57649. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57650. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57651. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57652. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57653. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57654. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57655. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57656. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57657. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57658. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57659. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57660. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57661. // Emitter
  57662. if (parsedParticleSystem.particleEmitterType) {
  57663. var emitterType = void 0;
  57664. switch (parsedParticleSystem.particleEmitterType.type) {
  57665. case "SphereEmitter":
  57666. emitterType = new BABYLON.SphereParticleEmitter();
  57667. break;
  57668. case "SphereDirectedParticleEmitter":
  57669. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57670. break;
  57671. case "ConeEmitter":
  57672. emitterType = new BABYLON.ConeParticleEmitter();
  57673. break;
  57674. case "BoxEmitter":
  57675. default:
  57676. emitterType = new BABYLON.BoxParticleEmitter();
  57677. break;
  57678. }
  57679. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57680. particleSystem.particleEmitterType = emitterType;
  57681. }
  57682. return particleSystem;
  57683. };
  57684. return GPUParticleSystem;
  57685. }());
  57686. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57687. })(BABYLON || (BABYLON = {}));
  57688. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57689. var BABYLON;
  57690. (function (BABYLON) {
  57691. /**
  57692. * Represents one particle of a solid particle system.
  57693. */
  57694. var SolidParticle = /** @class */ (function () {
  57695. /**
  57696. * Creates a Solid Particle object.
  57697. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57698. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57699. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57700. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57701. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57702. * @param shapeId (integer) is the model shape identifier in the SPS.
  57703. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57704. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57705. */
  57706. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57707. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57708. /**
  57709. * particle global index
  57710. */
  57711. this.idx = 0;
  57712. /**
  57713. * The color of the particle
  57714. */
  57715. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57716. /**
  57717. * The world space position of the particle.
  57718. */
  57719. this.position = BABYLON.Vector3.Zero();
  57720. /**
  57721. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57722. */
  57723. this.rotation = BABYLON.Vector3.Zero();
  57724. /**
  57725. * The scaling of the particle.
  57726. */
  57727. this.scaling = BABYLON.Vector3.One();
  57728. /**
  57729. * The uvs of the particle.
  57730. */
  57731. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57732. /**
  57733. * The current speed of the particle.
  57734. */
  57735. this.velocity = BABYLON.Vector3.Zero();
  57736. /**
  57737. * The pivot point in the particle local space.
  57738. */
  57739. this.pivot = BABYLON.Vector3.Zero();
  57740. /**
  57741. * Must the particle be translated from its pivot point in its local space ?
  57742. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57743. * Default : false
  57744. */
  57745. this.translateFromPivot = false;
  57746. /**
  57747. * Is the particle active or not ?
  57748. */
  57749. this.alive = true;
  57750. /**
  57751. * Is the particle visible or not ?
  57752. */
  57753. this.isVisible = true;
  57754. /**
  57755. * Index of this particle in the global "positions" array (Internal use)
  57756. */
  57757. this._pos = 0;
  57758. /**
  57759. * Index of this particle in the global "indices" array (Internal use)
  57760. */
  57761. this._ind = 0;
  57762. /**
  57763. * ModelShape id of this particle
  57764. */
  57765. this.shapeId = 0;
  57766. /**
  57767. * Index of the particle in its shape id (Internal use)
  57768. */
  57769. this.idxInShape = 0;
  57770. /**
  57771. * Still set as invisible in order to skip useless computations (Internal use)
  57772. */
  57773. this._stillInvisible = false;
  57774. /**
  57775. * Last computed particle rotation matrix
  57776. */
  57777. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57778. /**
  57779. * Parent particle Id, if any.
  57780. * Default null.
  57781. */
  57782. this.parentId = null;
  57783. /**
  57784. * Internal global position in the SPS.
  57785. */
  57786. this._globalPosition = BABYLON.Vector3.Zero();
  57787. this.idx = particleIndex;
  57788. this._pos = positionIndex;
  57789. this._ind = indiceIndex;
  57790. this._model = model;
  57791. this.shapeId = shapeId;
  57792. this.idxInShape = idxInShape;
  57793. this._sps = sps;
  57794. if (modelBoundingInfo) {
  57795. this._modelBoundingInfo = modelBoundingInfo;
  57796. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57797. }
  57798. }
  57799. Object.defineProperty(SolidParticle.prototype, "scale", {
  57800. /**
  57801. * Legacy support, changed scale to scaling
  57802. */
  57803. get: function () {
  57804. return this.scaling;
  57805. },
  57806. /**
  57807. * Legacy support, changed scale to scaling
  57808. */
  57809. set: function (scale) {
  57810. this.scaling = scale;
  57811. },
  57812. enumerable: true,
  57813. configurable: true
  57814. });
  57815. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57816. /**
  57817. * Legacy support, changed quaternion to rotationQuaternion
  57818. */
  57819. get: function () {
  57820. return this.rotationQuaternion;
  57821. },
  57822. /**
  57823. * Legacy support, changed quaternion to rotationQuaternion
  57824. */
  57825. set: function (q) {
  57826. this.rotationQuaternion = q;
  57827. },
  57828. enumerable: true,
  57829. configurable: true
  57830. });
  57831. /**
  57832. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57833. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57834. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57835. * @returns true if it intersects
  57836. */
  57837. SolidParticle.prototype.intersectsMesh = function (target) {
  57838. if (!this._boundingInfo || !target._boundingInfo) {
  57839. return false;
  57840. }
  57841. if (this._sps._bSphereOnly) {
  57842. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57843. }
  57844. return this._boundingInfo.intersects(target._boundingInfo, false);
  57845. };
  57846. return SolidParticle;
  57847. }());
  57848. BABYLON.SolidParticle = SolidParticle;
  57849. /**
  57850. * Represents the shape of the model used by one particle of a solid particle system.
  57851. * SPS internal tool, don't use it manually.
  57852. */
  57853. var ModelShape = /** @class */ (function () {
  57854. /**
  57855. * 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.
  57856. * SPS internal tool, don't use it manually.
  57857. * @hidden
  57858. */
  57859. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57860. /**
  57861. * length of the shape in the model indices array (internal use)
  57862. */
  57863. this._indicesLength = 0;
  57864. this.shapeID = id;
  57865. this._shape = shape;
  57866. this._indicesLength = indicesLength;
  57867. this._shapeUV = shapeUV;
  57868. this._positionFunction = posFunction;
  57869. this._vertexFunction = vtxFunction;
  57870. }
  57871. return ModelShape;
  57872. }());
  57873. BABYLON.ModelShape = ModelShape;
  57874. /**
  57875. * Represents a Depth Sorted Particle in the solid particle system.
  57876. */
  57877. var DepthSortedParticle = /** @class */ (function () {
  57878. function DepthSortedParticle() {
  57879. /**
  57880. * Index of the particle in the "indices" array
  57881. */
  57882. this.ind = 0;
  57883. /**
  57884. * Length of the particle shape in the "indices" array
  57885. */
  57886. this.indicesLength = 0;
  57887. /**
  57888. * Squared distance from the particle to the camera
  57889. */
  57890. this.sqDistance = 0.0;
  57891. }
  57892. return DepthSortedParticle;
  57893. }());
  57894. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57895. })(BABYLON || (BABYLON = {}));
  57896. //# sourceMappingURL=babylon.solidParticle.js.map
  57897. var BABYLON;
  57898. (function (BABYLON) {
  57899. /**
  57900. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57901. *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.
  57902. * The SPS is also a particle system. It provides some methods to manage the particles.
  57903. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57904. *
  57905. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57906. */
  57907. var SolidParticleSystem = /** @class */ (function () {
  57908. /**
  57909. * Creates a SPS (Solid Particle System) object.
  57910. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57911. * @param scene (Scene) is the scene in which the SPS is added.
  57912. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57913. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57914. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57915. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57916. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57917. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57918. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57919. */
  57920. function SolidParticleSystem(name, scene, options) {
  57921. /**
  57922. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57923. * Example : var p = SPS.particles[i];
  57924. */
  57925. this.particles = new Array();
  57926. /**
  57927. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57928. */
  57929. this.nbParticles = 0;
  57930. /**
  57931. * If the particles must ever face the camera (default false). Useful for planar particles.
  57932. */
  57933. this.billboard = false;
  57934. /**
  57935. * Recompute normals when adding a shape
  57936. */
  57937. this.recomputeNormals = true;
  57938. /**
  57939. * This a counter ofr your own usage. It's not set by any SPS functions.
  57940. */
  57941. this.counter = 0;
  57942. /**
  57943. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57944. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57945. */
  57946. this.vars = {};
  57947. /**
  57948. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57949. */
  57950. this._bSphereOnly = false;
  57951. /**
  57952. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57953. */
  57954. this._bSphereRadiusFactor = 1.0;
  57955. this._positions = new Array();
  57956. this._indices = new Array();
  57957. this._normals = new Array();
  57958. this._colors = new Array();
  57959. this._uvs = new Array();
  57960. this._index = 0; // indices index
  57961. this._updatable = true;
  57962. this._pickable = false;
  57963. this._isVisibilityBoxLocked = false;
  57964. this._alwaysVisible = false;
  57965. this._depthSort = false;
  57966. this._shapeCounter = 0;
  57967. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57968. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57969. this._computeParticleColor = true;
  57970. this._computeParticleTexture = true;
  57971. this._computeParticleRotation = true;
  57972. this._computeParticleVertex = false;
  57973. this._computeBoundingBox = false;
  57974. this._depthSortParticles = true;
  57975. this._cam_axisZ = BABYLON.Vector3.Zero();
  57976. this._cam_axisY = BABYLON.Vector3.Zero();
  57977. this._cam_axisX = BABYLON.Vector3.Zero();
  57978. this._axisZ = BABYLON.Axis.Z;
  57979. this._camDir = BABYLON.Vector3.Zero();
  57980. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57981. this._rotMatrix = new BABYLON.Matrix();
  57982. this._invertMatrix = new BABYLON.Matrix();
  57983. this._rotated = BABYLON.Vector3.Zero();
  57984. this._quaternion = new BABYLON.Quaternion();
  57985. this._vertex = BABYLON.Vector3.Zero();
  57986. this._normal = BABYLON.Vector3.Zero();
  57987. this._yaw = 0.0;
  57988. this._pitch = 0.0;
  57989. this._roll = 0.0;
  57990. this._halfroll = 0.0;
  57991. this._halfpitch = 0.0;
  57992. this._halfyaw = 0.0;
  57993. this._sinRoll = 0.0;
  57994. this._cosRoll = 0.0;
  57995. this._sinPitch = 0.0;
  57996. this._cosPitch = 0.0;
  57997. this._sinYaw = 0.0;
  57998. this._cosYaw = 0.0;
  57999. this._mustUnrotateFixedNormals = false;
  58000. this._minimum = BABYLON.Vector3.Zero();
  58001. this._maximum = BABYLON.Vector3.Zero();
  58002. this._minBbox = BABYLON.Vector3.Zero();
  58003. this._maxBbox = BABYLON.Vector3.Zero();
  58004. this._particlesIntersect = false;
  58005. this._depthSortFunction = function (p1, p2) {
  58006. return (p2.sqDistance - p1.sqDistance);
  58007. };
  58008. this._needs32Bits = false;
  58009. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58010. this._scaledPivot = BABYLON.Vector3.Zero();
  58011. this._particleHasParent = false;
  58012. this.name = name;
  58013. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58014. this._camera = scene.activeCamera;
  58015. this._pickable = options ? options.isPickable : false;
  58016. this._depthSort = options ? options.enableDepthSort : false;
  58017. this._particlesIntersect = options ? options.particleIntersection : false;
  58018. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58019. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58020. if (options && options.updatable) {
  58021. this._updatable = options.updatable;
  58022. }
  58023. else {
  58024. this._updatable = true;
  58025. }
  58026. if (this._pickable) {
  58027. this.pickedParticles = [];
  58028. }
  58029. if (this._depthSort) {
  58030. this.depthSortedParticles = [];
  58031. }
  58032. }
  58033. /**
  58034. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58035. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58036. * @returns the created mesh
  58037. */
  58038. SolidParticleSystem.prototype.buildMesh = function () {
  58039. if (this.nbParticles === 0) {
  58040. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58041. this.addShape(triangle, 1);
  58042. triangle.dispose();
  58043. }
  58044. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58045. this._positions32 = new Float32Array(this._positions);
  58046. this._uvs32 = new Float32Array(this._uvs);
  58047. this._colors32 = new Float32Array(this._colors);
  58048. if (this.recomputeNormals) {
  58049. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58050. }
  58051. this._normals32 = new Float32Array(this._normals);
  58052. this._fixedNormal32 = new Float32Array(this._normals);
  58053. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58054. this._unrotateFixedNormals();
  58055. }
  58056. var vertexData = new BABYLON.VertexData();
  58057. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58058. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58059. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58060. if (this._uvs32) {
  58061. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58062. ;
  58063. }
  58064. if (this._colors32) {
  58065. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58066. }
  58067. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58068. vertexData.applyToMesh(mesh, this._updatable);
  58069. this.mesh = mesh;
  58070. this.mesh.isPickable = this._pickable;
  58071. // free memory
  58072. if (!this._depthSort) {
  58073. this._indices = null;
  58074. }
  58075. this._positions = null;
  58076. this._normals = null;
  58077. this._uvs = null;
  58078. this._colors = null;
  58079. if (!this._updatable) {
  58080. this.particles.length = 0;
  58081. }
  58082. return mesh;
  58083. };
  58084. /**
  58085. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58086. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58087. * Thus the particles generated from `digest()` have their property `position` set yet.
  58088. * @param mesh ( Mesh ) is the mesh to be digested
  58089. * @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
  58090. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58091. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58092. * @returns the current SPS
  58093. */
  58094. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58095. var size = (options && options.facetNb) || 1;
  58096. var number = (options && options.number) || 0;
  58097. var delta = (options && options.delta) || 0;
  58098. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58099. var meshInd = mesh.getIndices();
  58100. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58101. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58102. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58103. var f = 0; // facet counter
  58104. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58105. // compute size from number
  58106. if (number) {
  58107. number = (number > totalFacets) ? totalFacets : number;
  58108. size = Math.round(totalFacets / number);
  58109. delta = 0;
  58110. }
  58111. else {
  58112. size = (size > totalFacets) ? totalFacets : size;
  58113. }
  58114. var facetPos = []; // submesh positions
  58115. var facetInd = []; // submesh indices
  58116. var facetUV = []; // submesh UV
  58117. var facetCol = []; // submesh colors
  58118. var barycenter = BABYLON.Vector3.Zero();
  58119. var sizeO = size;
  58120. while (f < totalFacets) {
  58121. size = sizeO + Math.floor((1 + delta) * Math.random());
  58122. if (f > totalFacets - size) {
  58123. size = totalFacets - f;
  58124. }
  58125. // reset temp arrays
  58126. facetPos.length = 0;
  58127. facetInd.length = 0;
  58128. facetUV.length = 0;
  58129. facetCol.length = 0;
  58130. // iterate over "size" facets
  58131. var fi = 0;
  58132. for (var j = f * 3; j < (f + size) * 3; j++) {
  58133. facetInd.push(fi);
  58134. var i = meshInd[j];
  58135. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58136. if (meshUV) {
  58137. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58138. }
  58139. if (meshCol) {
  58140. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58141. }
  58142. fi++;
  58143. }
  58144. // create a model shape for each single particle
  58145. var idx = this.nbParticles;
  58146. var shape = this._posToShape(facetPos);
  58147. var shapeUV = this._uvsToShapeUV(facetUV);
  58148. // compute the barycenter of the shape
  58149. var v;
  58150. for (v = 0; v < shape.length; v++) {
  58151. barycenter.addInPlace(shape[v]);
  58152. }
  58153. barycenter.scaleInPlace(1 / shape.length);
  58154. // shift the shape from its barycenter to the origin
  58155. for (v = 0; v < shape.length; v++) {
  58156. shape[v].subtractInPlace(barycenter);
  58157. }
  58158. var bInfo;
  58159. if (this._particlesIntersect) {
  58160. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58161. }
  58162. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58163. // add the particle in the SPS
  58164. var currentPos = this._positions.length;
  58165. var currentInd = this._indices.length;
  58166. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58167. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58168. // initialize the particle position
  58169. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58170. this._index += shape.length;
  58171. idx++;
  58172. this.nbParticles++;
  58173. this._shapeCounter++;
  58174. f += size;
  58175. }
  58176. return this;
  58177. };
  58178. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58179. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58180. var index = 0;
  58181. var idx = 0;
  58182. for (var p = 0; p < this.particles.length; p++) {
  58183. this._particle = this.particles[p];
  58184. this._shape = this._particle._model._shape;
  58185. if (this._particle.rotationQuaternion) {
  58186. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58187. }
  58188. else {
  58189. this._yaw = this._particle.rotation.y;
  58190. this._pitch = this._particle.rotation.x;
  58191. this._roll = this._particle.rotation.z;
  58192. this._quaternionRotationYPR();
  58193. }
  58194. this._quaternionToRotationMatrix();
  58195. this._rotMatrix.invertToRef(this._invertMatrix);
  58196. for (var pt = 0; pt < this._shape.length; pt++) {
  58197. idx = index + pt * 3;
  58198. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58199. this._fixedNormal32[idx] = this._normal.x;
  58200. this._fixedNormal32[idx + 1] = this._normal.y;
  58201. this._fixedNormal32[idx + 2] = this._normal.z;
  58202. }
  58203. index = idx + 3;
  58204. }
  58205. };
  58206. //reset copy
  58207. SolidParticleSystem.prototype._resetCopy = function () {
  58208. this._copy.position.x = 0;
  58209. this._copy.position.y = 0;
  58210. this._copy.position.z = 0;
  58211. this._copy.rotation.x = 0;
  58212. this._copy.rotation.y = 0;
  58213. this._copy.rotation.z = 0;
  58214. this._copy.rotationQuaternion = null;
  58215. this._copy.scaling.x = 1.0;
  58216. this._copy.scaling.y = 1.0;
  58217. this._copy.scaling.z = 1.0;
  58218. this._copy.uvs.x = 0;
  58219. this._copy.uvs.y = 0;
  58220. this._copy.uvs.z = 1.0;
  58221. this._copy.uvs.w = 1.0;
  58222. this._copy.color = null;
  58223. this._copy.translateFromPivot = false;
  58224. };
  58225. // _meshBuilder : inserts the shape model in the global SPS mesh
  58226. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58227. var i;
  58228. var u = 0;
  58229. var c = 0;
  58230. var n = 0;
  58231. this._resetCopy();
  58232. if (options && options.positionFunction) { // call to custom positionFunction
  58233. options.positionFunction(this._copy, idx, idxInShape);
  58234. this._mustUnrotateFixedNormals = true;
  58235. }
  58236. if (this._copy.rotationQuaternion) {
  58237. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58238. }
  58239. else {
  58240. this._yaw = this._copy.rotation.y;
  58241. this._pitch = this._copy.rotation.x;
  58242. this._roll = this._copy.rotation.z;
  58243. this._quaternionRotationYPR();
  58244. }
  58245. this._quaternionToRotationMatrix();
  58246. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58247. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58248. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58249. if (this._copy.translateFromPivot) {
  58250. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58251. }
  58252. else {
  58253. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58254. }
  58255. for (i = 0; i < shape.length; i++) {
  58256. this._vertex.x = shape[i].x;
  58257. this._vertex.y = shape[i].y;
  58258. this._vertex.z = shape[i].z;
  58259. if (options && options.vertexFunction) {
  58260. options.vertexFunction(this._copy, this._vertex, i);
  58261. }
  58262. this._vertex.x *= this._copy.scaling.x;
  58263. this._vertex.y *= this._copy.scaling.y;
  58264. this._vertex.z *= this._copy.scaling.z;
  58265. this._vertex.x -= this._scaledPivot.x;
  58266. this._vertex.y -= this._scaledPivot.y;
  58267. this._vertex.z -= this._scaledPivot.z;
  58268. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58269. this._rotated.addInPlace(this._pivotBackTranslation);
  58270. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58271. if (meshUV) {
  58272. 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);
  58273. u += 2;
  58274. }
  58275. if (this._copy.color) {
  58276. this._color = this._copy.color;
  58277. }
  58278. else if (meshCol && meshCol[c] !== undefined) {
  58279. this._color.r = meshCol[c];
  58280. this._color.g = meshCol[c + 1];
  58281. this._color.b = meshCol[c + 2];
  58282. this._color.a = meshCol[c + 3];
  58283. }
  58284. else {
  58285. this._color.r = 1.0;
  58286. this._color.g = 1.0;
  58287. this._color.b = 1.0;
  58288. this._color.a = 1.0;
  58289. }
  58290. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58291. c += 4;
  58292. if (!this.recomputeNormals && meshNor) {
  58293. this._normal.x = meshNor[n];
  58294. this._normal.y = meshNor[n + 1];
  58295. this._normal.z = meshNor[n + 2];
  58296. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58297. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58298. n += 3;
  58299. }
  58300. }
  58301. for (i = 0; i < meshInd.length; i++) {
  58302. var current_ind = p + meshInd[i];
  58303. indices.push(current_ind);
  58304. if (current_ind > 65535) {
  58305. this._needs32Bits = true;
  58306. }
  58307. }
  58308. if (this._pickable) {
  58309. var nbfaces = meshInd.length / 3;
  58310. for (i = 0; i < nbfaces; i++) {
  58311. this.pickedParticles.push({ idx: idx, faceId: i });
  58312. }
  58313. }
  58314. if (this._depthSort) {
  58315. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58316. }
  58317. return this._copy;
  58318. };
  58319. // returns a shape array from positions array
  58320. SolidParticleSystem.prototype._posToShape = function (positions) {
  58321. var shape = [];
  58322. for (var i = 0; i < positions.length; i += 3) {
  58323. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58324. }
  58325. return shape;
  58326. };
  58327. // returns a shapeUV array from a Vector4 uvs
  58328. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58329. var shapeUV = [];
  58330. if (uvs) {
  58331. for (var i = 0; i < uvs.length; i++)
  58332. shapeUV.push(uvs[i]);
  58333. }
  58334. return shapeUV;
  58335. };
  58336. // adds a new particle object in the particles array
  58337. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58338. if (bInfo === void 0) { bInfo = null; }
  58339. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58340. this.particles.push(sp);
  58341. return sp;
  58342. };
  58343. /**
  58344. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58345. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58346. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58347. * @param nb (positive integer) the number of particles to be created from this model
  58348. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58349. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58350. * @returns the number of shapes in the system
  58351. */
  58352. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58353. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58354. var meshInd = mesh.getIndices();
  58355. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58356. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58357. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58358. var bbInfo;
  58359. if (this._particlesIntersect) {
  58360. bbInfo = mesh.getBoundingInfo();
  58361. }
  58362. var shape = this._posToShape(meshPos);
  58363. var shapeUV = this._uvsToShapeUV(meshUV);
  58364. var posfunc = options ? options.positionFunction : null;
  58365. var vtxfunc = options ? options.vertexFunction : null;
  58366. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58367. // particles
  58368. var sp;
  58369. var currentCopy;
  58370. var idx = this.nbParticles;
  58371. for (var i = 0; i < nb; i++) {
  58372. var currentPos = this._positions.length;
  58373. var currentInd = this._indices.length;
  58374. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58375. if (this._updatable) {
  58376. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58377. sp.position.copyFrom(currentCopy.position);
  58378. sp.rotation.copyFrom(currentCopy.rotation);
  58379. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58380. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58381. }
  58382. if (currentCopy.color && sp.color) {
  58383. sp.color.copyFrom(currentCopy.color);
  58384. }
  58385. sp.scaling.copyFrom(currentCopy.scaling);
  58386. sp.uvs.copyFrom(currentCopy.uvs);
  58387. }
  58388. this._index += shape.length;
  58389. idx++;
  58390. }
  58391. this.nbParticles += nb;
  58392. this._shapeCounter++;
  58393. return this._shapeCounter - 1;
  58394. };
  58395. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58396. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58397. this._resetCopy();
  58398. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58399. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58400. }
  58401. if (this._copy.rotationQuaternion) {
  58402. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58403. }
  58404. else {
  58405. this._yaw = this._copy.rotation.y;
  58406. this._pitch = this._copy.rotation.x;
  58407. this._roll = this._copy.rotation.z;
  58408. this._quaternionRotationYPR();
  58409. }
  58410. this._quaternionToRotationMatrix();
  58411. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58412. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58413. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58414. if (this._copy.translateFromPivot) {
  58415. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58416. }
  58417. else {
  58418. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58419. }
  58420. this._shape = particle._model._shape;
  58421. for (var pt = 0; pt < this._shape.length; pt++) {
  58422. this._vertex.x = this._shape[pt].x;
  58423. this._vertex.y = this._shape[pt].y;
  58424. this._vertex.z = this._shape[pt].z;
  58425. if (particle._model._vertexFunction) {
  58426. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58427. }
  58428. this._vertex.x *= this._copy.scaling.x;
  58429. this._vertex.y *= this._copy.scaling.y;
  58430. this._vertex.z *= this._copy.scaling.z;
  58431. this._vertex.x -= this._scaledPivot.x;
  58432. this._vertex.y -= this._scaledPivot.y;
  58433. this._vertex.z -= this._scaledPivot.z;
  58434. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58435. this._rotated.addInPlace(this._pivotBackTranslation);
  58436. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58437. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58438. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58439. }
  58440. particle.position.x = 0.0;
  58441. particle.position.y = 0.0;
  58442. particle.position.z = 0.0;
  58443. particle.rotation.x = 0.0;
  58444. particle.rotation.y = 0.0;
  58445. particle.rotation.z = 0.0;
  58446. particle.rotationQuaternion = null;
  58447. particle.scaling.x = 1.0;
  58448. particle.scaling.y = 1.0;
  58449. particle.scaling.z = 1.0;
  58450. particle.uvs.x = 0.0;
  58451. particle.uvs.y = 0.0;
  58452. particle.uvs.z = 1.0;
  58453. particle.uvs.w = 1.0;
  58454. particle.pivot.x = 0.0;
  58455. particle.pivot.y = 0.0;
  58456. particle.pivot.z = 0.0;
  58457. particle.translateFromPivot = false;
  58458. particle.parentId = null;
  58459. };
  58460. /**
  58461. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58462. * @returns the SPS.
  58463. */
  58464. SolidParticleSystem.prototype.rebuildMesh = function () {
  58465. for (var p = 0; p < this.particles.length; p++) {
  58466. this._rebuildParticle(this.particles[p]);
  58467. }
  58468. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58469. return this;
  58470. };
  58471. /**
  58472. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58473. * This method calls `updateParticle()` for each particle of the SPS.
  58474. * For an animated SPS, it is usually called within the render loop.
  58475. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58476. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58477. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58478. * @returns the SPS.
  58479. */
  58480. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58481. if (start === void 0) { start = 0; }
  58482. if (end === void 0) { end = this.nbParticles - 1; }
  58483. if (update === void 0) { update = true; }
  58484. if (!this._updatable) {
  58485. return this;
  58486. }
  58487. // custom beforeUpdate
  58488. this.beforeUpdateParticles(start, end, update);
  58489. this._cam_axisX.x = 1.0;
  58490. this._cam_axisX.y = 0.0;
  58491. this._cam_axisX.z = 0.0;
  58492. this._cam_axisY.x = 0.0;
  58493. this._cam_axisY.y = 1.0;
  58494. this._cam_axisY.z = 0.0;
  58495. this._cam_axisZ.x = 0.0;
  58496. this._cam_axisZ.y = 0.0;
  58497. this._cam_axisZ.z = 1.0;
  58498. // cases when the World Matrix is to be computed first
  58499. if (this.billboard || this._depthSort) {
  58500. this.mesh.computeWorldMatrix(true);
  58501. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58502. }
  58503. // if the particles will always face the camera
  58504. if (this.billboard) {
  58505. // compute the camera position and un-rotate it by the current mesh rotation
  58506. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58507. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58508. this._cam_axisZ.normalize();
  58509. // same for camera up vector extracted from the cam view matrix
  58510. var view = this._camera.getViewMatrix(true);
  58511. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58512. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58513. this._cam_axisY.normalize();
  58514. this._cam_axisX.normalize();
  58515. }
  58516. // if depthSort, compute the camera global position in the mesh local system
  58517. if (this._depthSort) {
  58518. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58519. }
  58520. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58521. var idx = 0; // current position index in the global array positions32
  58522. var index = 0; // position start index in the global array positions32 of the current particle
  58523. var colidx = 0; // current color index in the global array colors32
  58524. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58525. var uvidx = 0; // current uv index in the global array uvs32
  58526. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58527. var pt = 0; // current index in the particle model shape
  58528. if (this.mesh.isFacetDataEnabled) {
  58529. this._computeBoundingBox = true;
  58530. }
  58531. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58532. if (this._computeBoundingBox) {
  58533. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58534. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58535. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58536. }
  58537. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58538. if (this.mesh._boundingInfo) {
  58539. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58540. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58541. }
  58542. }
  58543. }
  58544. // particle loop
  58545. index = this.particles[start]._pos;
  58546. var vpos = (index / 3) | 0;
  58547. colorIndex = vpos * 4;
  58548. uvIndex = vpos * 2;
  58549. for (var p = start; p <= end; p++) {
  58550. this._particle = this.particles[p];
  58551. this._shape = this._particle._model._shape;
  58552. this._shapeUV = this._particle._model._shapeUV;
  58553. // call to custom user function to update the particle properties
  58554. this.updateParticle(this._particle);
  58555. // camera-particle distance for depth sorting
  58556. if (this._depthSort && this._depthSortParticles) {
  58557. var dsp = this.depthSortedParticles[p];
  58558. dsp.ind = this._particle._ind;
  58559. dsp.indicesLength = this._particle._model._indicesLength;
  58560. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58561. }
  58562. // skip the computations for inactive or already invisible particles
  58563. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58564. // increment indexes for the next particle
  58565. pt = this._shape.length;
  58566. index += pt * 3;
  58567. colorIndex += pt * 4;
  58568. uvIndex += pt * 2;
  58569. continue;
  58570. }
  58571. if (this._particle.isVisible) {
  58572. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58573. this._particleHasParent = (this._particle.parentId !== null);
  58574. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58575. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58576. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58577. // particle rotation matrix
  58578. if (this.billboard) {
  58579. this._particle.rotation.x = 0.0;
  58580. this._particle.rotation.y = 0.0;
  58581. }
  58582. if (this._computeParticleRotation || this.billboard) {
  58583. if (this._particle.rotationQuaternion) {
  58584. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58585. }
  58586. else {
  58587. this._yaw = this._particle.rotation.y;
  58588. this._pitch = this._particle.rotation.x;
  58589. this._roll = this._particle.rotation.z;
  58590. this._quaternionRotationYPR();
  58591. }
  58592. this._quaternionToRotationMatrix();
  58593. }
  58594. if (this._particleHasParent) {
  58595. this._parent = this.particles[this._particle.parentId];
  58596. 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];
  58597. 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];
  58598. 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];
  58599. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58600. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58601. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58602. if (this._computeParticleRotation || this.billboard) {
  58603. 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];
  58604. 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];
  58605. 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];
  58606. 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];
  58607. 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];
  58608. 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];
  58609. 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];
  58610. 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];
  58611. 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];
  58612. }
  58613. }
  58614. else {
  58615. this._particle._globalPosition.x = this._particle.position.x;
  58616. this._particle._globalPosition.y = this._particle.position.y;
  58617. this._particle._globalPosition.z = this._particle.position.z;
  58618. if (this._computeParticleRotation || this.billboard) {
  58619. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58620. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58621. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58622. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58623. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58624. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58625. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58626. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58627. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58628. }
  58629. }
  58630. if (this._particle.translateFromPivot) {
  58631. this._pivotBackTranslation.x = 0.0;
  58632. this._pivotBackTranslation.y = 0.0;
  58633. this._pivotBackTranslation.z = 0.0;
  58634. }
  58635. else {
  58636. this._pivotBackTranslation.x = this._scaledPivot.x;
  58637. this._pivotBackTranslation.y = this._scaledPivot.y;
  58638. this._pivotBackTranslation.z = this._scaledPivot.z;
  58639. }
  58640. // particle vertex loop
  58641. for (pt = 0; pt < this._shape.length; pt++) {
  58642. idx = index + pt * 3;
  58643. colidx = colorIndex + pt * 4;
  58644. uvidx = uvIndex + pt * 2;
  58645. this._vertex.x = this._shape[pt].x;
  58646. this._vertex.y = this._shape[pt].y;
  58647. this._vertex.z = this._shape[pt].z;
  58648. if (this._computeParticleVertex) {
  58649. this.updateParticleVertex(this._particle, this._vertex, pt);
  58650. }
  58651. // positions
  58652. this._vertex.x *= this._particle.scaling.x;
  58653. this._vertex.y *= this._particle.scaling.y;
  58654. this._vertex.z *= this._particle.scaling.z;
  58655. this._vertex.x -= this._scaledPivot.x;
  58656. this._vertex.y -= this._scaledPivot.y;
  58657. this._vertex.z -= this._scaledPivot.z;
  58658. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58659. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58660. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58661. this._rotated.x += this._pivotBackTranslation.x;
  58662. this._rotated.y += this._pivotBackTranslation.y;
  58663. this._rotated.z += this._pivotBackTranslation.z;
  58664. 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;
  58665. 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;
  58666. 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;
  58667. if (this._computeBoundingBox) {
  58668. if (this._positions32[idx] < this._minimum.x) {
  58669. this._minimum.x = this._positions32[idx];
  58670. }
  58671. if (this._positions32[idx] > this._maximum.x) {
  58672. this._maximum.x = this._positions32[idx];
  58673. }
  58674. if (this._positions32[idx + 1] < this._minimum.y) {
  58675. this._minimum.y = this._positions32[idx + 1];
  58676. }
  58677. if (this._positions32[idx + 1] > this._maximum.y) {
  58678. this._maximum.y = this._positions32[idx + 1];
  58679. }
  58680. if (this._positions32[idx + 2] < this._minimum.z) {
  58681. this._minimum.z = this._positions32[idx + 2];
  58682. }
  58683. if (this._positions32[idx + 2] > this._maximum.z) {
  58684. this._maximum.z = this._positions32[idx + 2];
  58685. }
  58686. }
  58687. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58688. if (!this._computeParticleVertex) {
  58689. this._normal.x = this._fixedNormal32[idx];
  58690. this._normal.y = this._fixedNormal32[idx + 1];
  58691. this._normal.z = this._fixedNormal32[idx + 2];
  58692. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58693. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58694. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58695. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58696. 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;
  58697. 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;
  58698. }
  58699. if (this._computeParticleColor && this._particle.color) {
  58700. this._colors32[colidx] = this._particle.color.r;
  58701. this._colors32[colidx + 1] = this._particle.color.g;
  58702. this._colors32[colidx + 2] = this._particle.color.b;
  58703. this._colors32[colidx + 3] = this._particle.color.a;
  58704. }
  58705. if (this._computeParticleTexture) {
  58706. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58707. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58708. }
  58709. }
  58710. }
  58711. // particle just set invisible : scaled to zero and positioned at the origin
  58712. else {
  58713. this._particle._stillInvisible = true; // mark the particle as invisible
  58714. for (pt = 0; pt < this._shape.length; pt++) {
  58715. idx = index + pt * 3;
  58716. colidx = colorIndex + pt * 4;
  58717. uvidx = uvIndex + pt * 2;
  58718. this._positions32[idx] = 0.0;
  58719. this._positions32[idx + 1] = 0.0;
  58720. this._positions32[idx + 2] = 0.0;
  58721. this._normals32[idx] = 0.0;
  58722. this._normals32[idx + 1] = 0.0;
  58723. this._normals32[idx + 2] = 0.0;
  58724. if (this._computeParticleColor && this._particle.color) {
  58725. this._colors32[colidx] = this._particle.color.r;
  58726. this._colors32[colidx + 1] = this._particle.color.g;
  58727. this._colors32[colidx + 2] = this._particle.color.b;
  58728. this._colors32[colidx + 3] = this._particle.color.a;
  58729. }
  58730. if (this._computeParticleTexture) {
  58731. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58732. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58733. }
  58734. }
  58735. }
  58736. // if the particle intersections must be computed : update the bbInfo
  58737. if (this._particlesIntersect) {
  58738. var bInfo = this._particle._boundingInfo;
  58739. var bBox = bInfo.boundingBox;
  58740. var bSphere = bInfo.boundingSphere;
  58741. if (!this._bSphereOnly) {
  58742. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58743. for (var b = 0; b < bBox.vectors.length; b++) {
  58744. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58745. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58746. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58747. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58748. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58749. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58750. 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;
  58751. 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;
  58752. 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;
  58753. }
  58754. bBox._update(this.mesh._worldMatrix);
  58755. }
  58756. // place and scale the particle bouding sphere in the SPS local system, then update it
  58757. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58758. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58759. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58760. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58761. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58762. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58763. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58764. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58765. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58766. 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));
  58767. bSphere._update(this.mesh._worldMatrix);
  58768. }
  58769. // increment indexes for the next particle
  58770. index = idx + 3;
  58771. colorIndex = colidx + 4;
  58772. uvIndex = uvidx + 2;
  58773. }
  58774. // if the VBO must be updated
  58775. if (update) {
  58776. if (this._computeParticleColor) {
  58777. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58778. }
  58779. if (this._computeParticleTexture) {
  58780. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58781. }
  58782. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58783. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58784. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58785. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58786. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58787. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58788. for (var i = 0; i < this._normals32.length; i++) {
  58789. this._fixedNormal32[i] = this._normals32[i];
  58790. }
  58791. }
  58792. if (!this.mesh.areNormalsFrozen) {
  58793. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58794. }
  58795. }
  58796. if (this._depthSort && this._depthSortParticles) {
  58797. this.depthSortedParticles.sort(this._depthSortFunction);
  58798. var dspl = this.depthSortedParticles.length;
  58799. var sorted = 0;
  58800. var lind = 0;
  58801. var sind = 0;
  58802. var sid = 0;
  58803. for (sorted = 0; sorted < dspl; sorted++) {
  58804. lind = this.depthSortedParticles[sorted].indicesLength;
  58805. sind = this.depthSortedParticles[sorted].ind;
  58806. for (var i = 0; i < lind; i++) {
  58807. this._indices32[sid] = this._indices[sind + i];
  58808. sid++;
  58809. }
  58810. }
  58811. this.mesh.updateIndices(this._indices32);
  58812. }
  58813. }
  58814. if (this._computeBoundingBox) {
  58815. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58816. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58817. }
  58818. this.afterUpdateParticles(start, end, update);
  58819. return this;
  58820. };
  58821. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58822. this._halfroll = this._roll * 0.5;
  58823. this._halfpitch = this._pitch * 0.5;
  58824. this._halfyaw = this._yaw * 0.5;
  58825. this._sinRoll = Math.sin(this._halfroll);
  58826. this._cosRoll = Math.cos(this._halfroll);
  58827. this._sinPitch = Math.sin(this._halfpitch);
  58828. this._cosPitch = Math.cos(this._halfpitch);
  58829. this._sinYaw = Math.sin(this._halfyaw);
  58830. this._cosYaw = Math.cos(this._halfyaw);
  58831. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58832. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58833. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58834. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58835. };
  58836. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58837. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58838. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58839. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58840. this._rotMatrix.m[3] = 0;
  58841. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58842. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58843. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58844. this._rotMatrix.m[7] = 0;
  58845. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58846. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58847. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58848. this._rotMatrix.m[11] = 0;
  58849. this._rotMatrix.m[12] = 0;
  58850. this._rotMatrix.m[13] = 0;
  58851. this._rotMatrix.m[14] = 0;
  58852. this._rotMatrix.m[15] = 1.0;
  58853. };
  58854. /**
  58855. * Disposes the SPS.
  58856. */
  58857. SolidParticleSystem.prototype.dispose = function () {
  58858. this.mesh.dispose();
  58859. this.vars = null;
  58860. // drop references to internal big arrays for the GC
  58861. this._positions = null;
  58862. this._indices = null;
  58863. this._normals = null;
  58864. this._uvs = null;
  58865. this._colors = null;
  58866. this._indices32 = null;
  58867. this._positions32 = null;
  58868. this._normals32 = null;
  58869. this._fixedNormal32 = null;
  58870. this._uvs32 = null;
  58871. this._colors32 = null;
  58872. this.pickedParticles = null;
  58873. };
  58874. /**
  58875. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58876. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58877. * @returns the SPS.
  58878. */
  58879. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58880. if (!this._isVisibilityBoxLocked) {
  58881. this.mesh.refreshBoundingInfo();
  58882. }
  58883. return this;
  58884. };
  58885. /**
  58886. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58887. * @param size the size (float) of the visibility box
  58888. * note : this doesn't lock the SPS mesh bounding box.
  58889. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58890. */
  58891. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58892. var vis = size / 2;
  58893. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58894. };
  58895. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58896. /**
  58897. * Gets whether the SPS as always visible or not
  58898. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58899. */
  58900. get: function () {
  58901. return this._alwaysVisible;
  58902. },
  58903. /**
  58904. * Sets the SPS as always visible or not
  58905. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58906. */
  58907. set: function (val) {
  58908. this._alwaysVisible = val;
  58909. this.mesh.alwaysSelectAsActiveMesh = val;
  58910. },
  58911. enumerable: true,
  58912. configurable: true
  58913. });
  58914. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58915. /**
  58916. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58917. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58918. */
  58919. get: function () {
  58920. return this._isVisibilityBoxLocked;
  58921. },
  58922. /**
  58923. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58924. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58925. */
  58926. set: function (val) {
  58927. this._isVisibilityBoxLocked = val;
  58928. var boundingInfo = this.mesh.getBoundingInfo();
  58929. boundingInfo.isLocked = val;
  58930. },
  58931. enumerable: true,
  58932. configurable: true
  58933. });
  58934. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58935. /**
  58936. * Gets if `setParticles()` computes the particle rotations or not.
  58937. * Default value : true. The SPS is faster when it's set to false.
  58938. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58939. */
  58940. get: function () {
  58941. return this._computeParticleRotation;
  58942. },
  58943. /**
  58944. * Tells to `setParticles()` to compute the particle rotations or not.
  58945. * Default value : true. The SPS is faster when it's set to false.
  58946. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58947. */
  58948. set: function (val) {
  58949. this._computeParticleRotation = val;
  58950. },
  58951. enumerable: true,
  58952. configurable: true
  58953. });
  58954. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58955. /**
  58956. * Gets if `setParticles()` computes the particle colors or not.
  58957. * Default value : true. The SPS is faster when it's set to false.
  58958. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58959. */
  58960. get: function () {
  58961. return this._computeParticleColor;
  58962. },
  58963. /**
  58964. * Tells to `setParticles()` to compute the particle colors or not.
  58965. * Default value : true. The SPS is faster when it's set to false.
  58966. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58967. */
  58968. set: function (val) {
  58969. this._computeParticleColor = val;
  58970. },
  58971. enumerable: true,
  58972. configurable: true
  58973. });
  58974. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58975. /**
  58976. * Gets if `setParticles()` computes the particle textures or not.
  58977. * Default value : true. The SPS is faster when it's set to false.
  58978. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58979. */
  58980. get: function () {
  58981. return this._computeParticleTexture;
  58982. },
  58983. set: function (val) {
  58984. this._computeParticleTexture = val;
  58985. },
  58986. enumerable: true,
  58987. configurable: true
  58988. });
  58989. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58990. /**
  58991. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58992. * Default value : false. The SPS is faster when it's set to false.
  58993. * Note : the particle custom vertex positions aren't stored values.
  58994. */
  58995. get: function () {
  58996. return this._computeParticleVertex;
  58997. },
  58998. /**
  58999. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59000. * Default value : false. The SPS is faster when it's set to false.
  59001. * Note : the particle custom vertex positions aren't stored values.
  59002. */
  59003. set: function (val) {
  59004. this._computeParticleVertex = val;
  59005. },
  59006. enumerable: true,
  59007. configurable: true
  59008. });
  59009. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59010. /**
  59011. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59012. */
  59013. get: function () {
  59014. return this._computeBoundingBox;
  59015. },
  59016. /**
  59017. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59018. */
  59019. set: function (val) {
  59020. this._computeBoundingBox = val;
  59021. },
  59022. enumerable: true,
  59023. configurable: true
  59024. });
  59025. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59026. /**
  59027. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59028. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59029. * Default : `true`
  59030. */
  59031. get: function () {
  59032. return this._depthSortParticles;
  59033. },
  59034. /**
  59035. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59036. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59037. * Default : `true`
  59038. */
  59039. set: function (val) {
  59040. this._depthSortParticles = val;
  59041. },
  59042. enumerable: true,
  59043. configurable: true
  59044. });
  59045. // =======================================================================
  59046. // Particle behavior logic
  59047. // these following methods may be overwritten by the user to fit his needs
  59048. /**
  59049. * This function does nothing. It may be overwritten to set all the particle first values.
  59050. * The SPS doesn't call this function, you may have to call it by your own.
  59051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59052. */
  59053. SolidParticleSystem.prototype.initParticles = function () {
  59054. };
  59055. /**
  59056. * This function does nothing. It may be overwritten to recycle a particle.
  59057. * The SPS doesn't call this function, you may have to call it by your own.
  59058. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59059. * @param particle The particle to recycle
  59060. * @returns the recycled particle
  59061. */
  59062. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59063. return particle;
  59064. };
  59065. /**
  59066. * Updates a particle : this function should be overwritten by the user.
  59067. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59068. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59069. * @example : just set a particle position or velocity and recycle conditions
  59070. * @param particle The particle to update
  59071. * @returns the updated particle
  59072. */
  59073. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59074. return particle;
  59075. };
  59076. /**
  59077. * Updates a vertex of a particle : it can be overwritten by the user.
  59078. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59079. * @param particle the current particle
  59080. * @param vertex the current index of the current particle
  59081. * @param pt the index of the current vertex in the particle shape
  59082. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59083. * @example : just set a vertex particle position
  59084. * @returns the updated vertex
  59085. */
  59086. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59087. return vertex;
  59088. };
  59089. /**
  59090. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59091. * This does nothing and may be overwritten by the user.
  59092. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59093. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59094. * @param update the boolean update value actually passed to setParticles()
  59095. */
  59096. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59097. };
  59098. /**
  59099. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59100. * This will be passed three parameters.
  59101. * This does nothing and may be overwritten by the user.
  59102. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59103. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59104. * @param update the boolean update value actually passed to setParticles()
  59105. */
  59106. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59107. };
  59108. return SolidParticleSystem;
  59109. }());
  59110. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59111. })(BABYLON || (BABYLON = {}));
  59112. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59113. var BABYLON;
  59114. (function (BABYLON) {
  59115. var ShaderMaterial = /** @class */ (function (_super) {
  59116. __extends(ShaderMaterial, _super);
  59117. function ShaderMaterial(name, scene, shaderPath, options) {
  59118. var _this = _super.call(this, name, scene) || this;
  59119. _this._textures = {};
  59120. _this._textureArrays = {};
  59121. _this._floats = {};
  59122. _this._ints = {};
  59123. _this._floatsArrays = {};
  59124. _this._colors3 = {};
  59125. _this._colors3Arrays = {};
  59126. _this._colors4 = {};
  59127. _this._vectors2 = {};
  59128. _this._vectors3 = {};
  59129. _this._vectors4 = {};
  59130. _this._matrices = {};
  59131. _this._matrices3x3 = {};
  59132. _this._matrices2x2 = {};
  59133. _this._vectors2Arrays = {};
  59134. _this._vectors3Arrays = {};
  59135. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59136. _this._shaderPath = shaderPath;
  59137. options.needAlphaBlending = options.needAlphaBlending || false;
  59138. options.needAlphaTesting = options.needAlphaTesting || false;
  59139. options.attributes = options.attributes || ["position", "normal", "uv"];
  59140. options.uniforms = options.uniforms || ["worldViewProjection"];
  59141. options.uniformBuffers = options.uniformBuffers || [];
  59142. options.samplers = options.samplers || [];
  59143. options.defines = options.defines || [];
  59144. _this._options = options;
  59145. return _this;
  59146. }
  59147. ShaderMaterial.prototype.getClassName = function () {
  59148. return "ShaderMaterial";
  59149. };
  59150. ShaderMaterial.prototype.needAlphaBlending = function () {
  59151. return this._options.needAlphaBlending;
  59152. };
  59153. ShaderMaterial.prototype.needAlphaTesting = function () {
  59154. return this._options.needAlphaTesting;
  59155. };
  59156. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59157. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59158. this._options.uniforms.push(uniformName);
  59159. }
  59160. };
  59161. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59162. if (this._options.samplers.indexOf(name) === -1) {
  59163. this._options.samplers.push(name);
  59164. }
  59165. this._textures[name] = texture;
  59166. return this;
  59167. };
  59168. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59169. if (this._options.samplers.indexOf(name) === -1) {
  59170. this._options.samplers.push(name);
  59171. }
  59172. this._checkUniform(name);
  59173. this._textureArrays[name] = textures;
  59174. return this;
  59175. };
  59176. ShaderMaterial.prototype.setFloat = function (name, value) {
  59177. this._checkUniform(name);
  59178. this._floats[name] = value;
  59179. return this;
  59180. };
  59181. ShaderMaterial.prototype.setInt = function (name, value) {
  59182. this._checkUniform(name);
  59183. this._ints[name] = value;
  59184. return this;
  59185. };
  59186. ShaderMaterial.prototype.setFloats = function (name, value) {
  59187. this._checkUniform(name);
  59188. this._floatsArrays[name] = value;
  59189. return this;
  59190. };
  59191. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59192. this._checkUniform(name);
  59193. this._colors3[name] = value;
  59194. return this;
  59195. };
  59196. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59197. this._checkUniform(name);
  59198. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59199. color.toArray(arr, arr.length);
  59200. return arr;
  59201. }, []);
  59202. return this;
  59203. };
  59204. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59205. this._checkUniform(name);
  59206. this._colors4[name] = value;
  59207. return this;
  59208. };
  59209. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59210. this._checkUniform(name);
  59211. this._vectors2[name] = value;
  59212. return this;
  59213. };
  59214. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59215. this._checkUniform(name);
  59216. this._vectors3[name] = value;
  59217. return this;
  59218. };
  59219. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59220. this._checkUniform(name);
  59221. this._vectors4[name] = value;
  59222. return this;
  59223. };
  59224. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59225. this._checkUniform(name);
  59226. this._matrices[name] = value;
  59227. return this;
  59228. };
  59229. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59230. this._checkUniform(name);
  59231. this._matrices3x3[name] = value;
  59232. return this;
  59233. };
  59234. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59235. this._checkUniform(name);
  59236. this._matrices2x2[name] = value;
  59237. return this;
  59238. };
  59239. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59240. this._checkUniform(name);
  59241. this._vectors2Arrays[name] = value;
  59242. return this;
  59243. };
  59244. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59245. this._checkUniform(name);
  59246. this._vectors3Arrays[name] = value;
  59247. return this;
  59248. };
  59249. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59250. if (!mesh) {
  59251. return true;
  59252. }
  59253. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59254. return false;
  59255. }
  59256. return false;
  59257. };
  59258. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59259. var scene = this.getScene();
  59260. var engine = scene.getEngine();
  59261. if (!this.checkReadyOnEveryCall) {
  59262. if (this._renderId === scene.getRenderId()) {
  59263. if (this._checkCache(scene, mesh, useInstances)) {
  59264. return true;
  59265. }
  59266. }
  59267. }
  59268. // Instances
  59269. var defines = [];
  59270. var attribs = [];
  59271. var fallbacks = new BABYLON.EffectFallbacks();
  59272. if (useInstances) {
  59273. defines.push("#define INSTANCES");
  59274. }
  59275. for (var index = 0; index < this._options.defines.length; index++) {
  59276. defines.push(this._options.defines[index]);
  59277. }
  59278. for (var index = 0; index < this._options.attributes.length; index++) {
  59279. attribs.push(this._options.attributes[index]);
  59280. }
  59281. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59282. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59283. defines.push("#define VERTEXCOLOR");
  59284. }
  59285. // Bones
  59286. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59289. if (mesh.numBoneInfluencers > 4) {
  59290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59292. }
  59293. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59294. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59295. fallbacks.addCPUSkinningFallback(0, mesh);
  59296. if (this._options.uniforms.indexOf("mBones") === -1) {
  59297. this._options.uniforms.push("mBones");
  59298. }
  59299. }
  59300. else {
  59301. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59302. }
  59303. // Textures
  59304. for (var name in this._textures) {
  59305. if (!this._textures[name].isReady()) {
  59306. return false;
  59307. }
  59308. }
  59309. // Alpha test
  59310. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59311. defines.push("#define ALPHATEST");
  59312. }
  59313. var previousEffect = this._effect;
  59314. var join = defines.join("\n");
  59315. this._effect = engine.createEffect(this._shaderPath, {
  59316. attributes: attribs,
  59317. uniformsNames: this._options.uniforms,
  59318. uniformBuffersNames: this._options.uniformBuffers,
  59319. samplers: this._options.samplers,
  59320. defines: join,
  59321. fallbacks: fallbacks,
  59322. onCompiled: this.onCompiled,
  59323. onError: this.onError
  59324. }, engine);
  59325. if (!this._effect.isReady()) {
  59326. return false;
  59327. }
  59328. if (previousEffect !== this._effect) {
  59329. scene.resetCachedMaterial();
  59330. }
  59331. this._renderId = scene.getRenderId();
  59332. return true;
  59333. };
  59334. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59335. var scene = this.getScene();
  59336. if (!this._effect) {
  59337. return;
  59338. }
  59339. if (this._options.uniforms.indexOf("world") !== -1) {
  59340. this._effect.setMatrix("world", world);
  59341. }
  59342. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59343. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59344. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59345. }
  59346. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59347. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59348. }
  59349. };
  59350. ShaderMaterial.prototype.bind = function (world, mesh) {
  59351. // Std values
  59352. this.bindOnlyWorldMatrix(world);
  59353. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59354. if (this._options.uniforms.indexOf("view") !== -1) {
  59355. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59356. }
  59357. if (this._options.uniforms.indexOf("projection") !== -1) {
  59358. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59359. }
  59360. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59361. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59362. }
  59363. // Bones
  59364. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59365. var name;
  59366. // Texture
  59367. for (name in this._textures) {
  59368. this._effect.setTexture(name, this._textures[name]);
  59369. }
  59370. // Texture arrays
  59371. for (name in this._textureArrays) {
  59372. this._effect.setTextureArray(name, this._textureArrays[name]);
  59373. }
  59374. // Int
  59375. for (name in this._ints) {
  59376. this._effect.setInt(name, this._ints[name]);
  59377. }
  59378. // Float
  59379. for (name in this._floats) {
  59380. this._effect.setFloat(name, this._floats[name]);
  59381. }
  59382. // Floats
  59383. for (name in this._floatsArrays) {
  59384. this._effect.setArray(name, this._floatsArrays[name]);
  59385. }
  59386. // Color3
  59387. for (name in this._colors3) {
  59388. this._effect.setColor3(name, this._colors3[name]);
  59389. }
  59390. for (name in this._colors3Arrays) {
  59391. this._effect.setArray3(name, this._colors3Arrays[name]);
  59392. }
  59393. // Color4
  59394. for (name in this._colors4) {
  59395. var color = this._colors4[name];
  59396. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59397. }
  59398. // Vector2
  59399. for (name in this._vectors2) {
  59400. this._effect.setVector2(name, this._vectors2[name]);
  59401. }
  59402. // Vector3
  59403. for (name in this._vectors3) {
  59404. this._effect.setVector3(name, this._vectors3[name]);
  59405. }
  59406. // Vector4
  59407. for (name in this._vectors4) {
  59408. this._effect.setVector4(name, this._vectors4[name]);
  59409. }
  59410. // Matrix
  59411. for (name in this._matrices) {
  59412. this._effect.setMatrix(name, this._matrices[name]);
  59413. }
  59414. // Matrix 3x3
  59415. for (name in this._matrices3x3) {
  59416. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59417. }
  59418. // Matrix 2x2
  59419. for (name in this._matrices2x2) {
  59420. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59421. }
  59422. // Vector2Array
  59423. for (name in this._vectors2Arrays) {
  59424. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59425. }
  59426. // Vector3Array
  59427. for (name in this._vectors3Arrays) {
  59428. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59429. }
  59430. }
  59431. this._afterBind(mesh);
  59432. };
  59433. ShaderMaterial.prototype.getActiveTextures = function () {
  59434. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59435. for (var name in this._textures) {
  59436. activeTextures.push(this._textures[name]);
  59437. }
  59438. for (var name in this._textureArrays) {
  59439. var array = this._textureArrays[name];
  59440. for (var index = 0; index < array.length; index++) {
  59441. activeTextures.push(array[index]);
  59442. }
  59443. }
  59444. return activeTextures;
  59445. };
  59446. ShaderMaterial.prototype.hasTexture = function (texture) {
  59447. if (_super.prototype.hasTexture.call(this, texture)) {
  59448. return true;
  59449. }
  59450. for (var name in this._textures) {
  59451. if (this._textures[name] === texture) {
  59452. return true;
  59453. }
  59454. }
  59455. for (var name in this._textureArrays) {
  59456. var array = this._textureArrays[name];
  59457. for (var index = 0; index < array.length; index++) {
  59458. if (array[index] === texture) {
  59459. return true;
  59460. }
  59461. }
  59462. }
  59463. return false;
  59464. };
  59465. ShaderMaterial.prototype.clone = function (name) {
  59466. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59467. return newShaderMaterial;
  59468. };
  59469. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59470. if (forceDisposeTextures) {
  59471. var name;
  59472. for (name in this._textures) {
  59473. this._textures[name].dispose();
  59474. }
  59475. for (name in this._textureArrays) {
  59476. var array = this._textureArrays[name];
  59477. for (var index = 0; index < array.length; index++) {
  59478. array[index].dispose();
  59479. }
  59480. }
  59481. }
  59482. this._textures = {};
  59483. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59484. };
  59485. ShaderMaterial.prototype.serialize = function () {
  59486. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59487. serializationObject.customType = "BABYLON.ShaderMaterial";
  59488. serializationObject.options = this._options;
  59489. serializationObject.shaderPath = this._shaderPath;
  59490. var name;
  59491. // Texture
  59492. serializationObject.textures = {};
  59493. for (name in this._textures) {
  59494. serializationObject.textures[name] = this._textures[name].serialize();
  59495. }
  59496. // Texture arrays
  59497. serializationObject.textureArrays = {};
  59498. for (name in this._textureArrays) {
  59499. serializationObject.textureArrays[name] = [];
  59500. var array = this._textureArrays[name];
  59501. for (var index = 0; index < array.length; index++) {
  59502. serializationObject.textureArrays[name].push(array[index].serialize());
  59503. }
  59504. }
  59505. // Float
  59506. serializationObject.floats = {};
  59507. for (name in this._floats) {
  59508. serializationObject.floats[name] = this._floats[name];
  59509. }
  59510. // Float s
  59511. serializationObject.FloatArrays = {};
  59512. for (name in this._floatsArrays) {
  59513. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59514. }
  59515. // Color3
  59516. serializationObject.colors3 = {};
  59517. for (name in this._colors3) {
  59518. serializationObject.colors3[name] = this._colors3[name].asArray();
  59519. }
  59520. // Color3 array
  59521. serializationObject.colors3Arrays = {};
  59522. for (name in this._colors3Arrays) {
  59523. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59524. }
  59525. // Color4
  59526. serializationObject.colors4 = {};
  59527. for (name in this._colors4) {
  59528. serializationObject.colors4[name] = this._colors4[name].asArray();
  59529. }
  59530. // Vector2
  59531. serializationObject.vectors2 = {};
  59532. for (name in this._vectors2) {
  59533. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59534. }
  59535. // Vector3
  59536. serializationObject.vectors3 = {};
  59537. for (name in this._vectors3) {
  59538. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59539. }
  59540. // Vector4
  59541. serializationObject.vectors4 = {};
  59542. for (name in this._vectors4) {
  59543. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59544. }
  59545. // Matrix
  59546. serializationObject.matrices = {};
  59547. for (name in this._matrices) {
  59548. serializationObject.matrices[name] = this._matrices[name].asArray();
  59549. }
  59550. // Matrix 3x3
  59551. serializationObject.matrices3x3 = {};
  59552. for (name in this._matrices3x3) {
  59553. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59554. }
  59555. // Matrix 2x2
  59556. serializationObject.matrices2x2 = {};
  59557. for (name in this._matrices2x2) {
  59558. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59559. }
  59560. // Vector2Array
  59561. serializationObject.vectors2Arrays = {};
  59562. for (name in this._vectors2Arrays) {
  59563. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59564. }
  59565. // Vector3Array
  59566. serializationObject.vectors3Arrays = {};
  59567. for (name in this._vectors3Arrays) {
  59568. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59569. }
  59570. return serializationObject;
  59571. };
  59572. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59573. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59574. var name;
  59575. // Texture
  59576. for (name in source.textures) {
  59577. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59578. }
  59579. // Texture arrays
  59580. for (name in source.textureArrays) {
  59581. var array = source.textureArrays[name];
  59582. var textureArray = new Array();
  59583. for (var index = 0; index < array.length; index++) {
  59584. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59585. }
  59586. material.setTextureArray(name, textureArray);
  59587. }
  59588. // Float
  59589. for (name in source.floats) {
  59590. material.setFloat(name, source.floats[name]);
  59591. }
  59592. // Float s
  59593. for (name in source.floatsArrays) {
  59594. material.setFloats(name, source.floatsArrays[name]);
  59595. }
  59596. // Color3
  59597. for (name in source.colors3) {
  59598. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59599. }
  59600. // Color3 arrays
  59601. for (name in source.colors3Arrays) {
  59602. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59603. if (i % 3 === 0) {
  59604. arr.push([num]);
  59605. }
  59606. else {
  59607. arr[arr.length - 1].push(num);
  59608. }
  59609. return arr;
  59610. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59611. material.setColor3Array(name, colors);
  59612. }
  59613. // Color4
  59614. for (name in source.colors4) {
  59615. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59616. }
  59617. // Vector2
  59618. for (name in source.vectors2) {
  59619. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59620. }
  59621. // Vector3
  59622. for (name in source.vectors3) {
  59623. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59624. }
  59625. // Vector4
  59626. for (name in source.vectors4) {
  59627. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59628. }
  59629. // Matrix
  59630. for (name in source.matrices) {
  59631. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59632. }
  59633. // Matrix 3x3
  59634. for (name in source.matrices3x3) {
  59635. material.setMatrix3x3(name, source.matrices3x3[name]);
  59636. }
  59637. // Matrix 2x2
  59638. for (name in source.matrices2x2) {
  59639. material.setMatrix2x2(name, source.matrices2x2[name]);
  59640. }
  59641. // Vector2Array
  59642. for (name in source.vectors2Arrays) {
  59643. material.setArray2(name, source.vectors2Arrays[name]);
  59644. }
  59645. // Vector3Array
  59646. for (name in source.vectors3Arrays) {
  59647. material.setArray3(name, source.vectors3Arrays[name]);
  59648. }
  59649. return material;
  59650. };
  59651. return ShaderMaterial;
  59652. }(BABYLON.Material));
  59653. BABYLON.ShaderMaterial = ShaderMaterial;
  59654. })(BABYLON || (BABYLON = {}));
  59655. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59656. var BABYLON;
  59657. (function (BABYLON) {
  59658. var GroundMesh = /** @class */ (function (_super) {
  59659. __extends(GroundMesh, _super);
  59660. function GroundMesh(name, scene) {
  59661. var _this = _super.call(this, name, scene) || this;
  59662. _this.generateOctree = false;
  59663. return _this;
  59664. }
  59665. GroundMesh.prototype.getClassName = function () {
  59666. return "GroundMesh";
  59667. };
  59668. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59669. get: function () {
  59670. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59671. },
  59672. enumerable: true,
  59673. configurable: true
  59674. });
  59675. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59676. get: function () {
  59677. return this._subdivisionsX;
  59678. },
  59679. enumerable: true,
  59680. configurable: true
  59681. });
  59682. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59683. get: function () {
  59684. return this._subdivisionsY;
  59685. },
  59686. enumerable: true,
  59687. configurable: true
  59688. });
  59689. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59690. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59691. this._subdivisionsX = chunksCount;
  59692. this._subdivisionsY = chunksCount;
  59693. this.subdivide(chunksCount);
  59694. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59695. };
  59696. /**
  59697. * Returns a height (y) value in the Worl system :
  59698. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59699. * Returns the ground y position if (x, z) are outside the ground surface.
  59700. */
  59701. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59702. var world = this.getWorldMatrix();
  59703. var invMat = BABYLON.Tmp.Matrix[5];
  59704. world.invertToRef(invMat);
  59705. var tmpVect = BABYLON.Tmp.Vector3[8];
  59706. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59707. x = tmpVect.x;
  59708. z = tmpVect.z;
  59709. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59710. return this.position.y;
  59711. }
  59712. if (!this._heightQuads || this._heightQuads.length == 0) {
  59713. this._initHeightQuads();
  59714. this._computeHeightQuads();
  59715. }
  59716. var facet = this._getFacetAt(x, z);
  59717. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59718. // return y in the World system
  59719. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59720. return tmpVect.y;
  59721. };
  59722. /**
  59723. * Returns a normalized vector (Vector3) orthogonal to the ground
  59724. * at the ground coordinates (x, z) expressed in the World system.
  59725. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59726. */
  59727. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59728. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59729. this.getNormalAtCoordinatesToRef(x, z, normal);
  59730. return normal;
  59731. };
  59732. /**
  59733. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59734. * at the ground coordinates (x, z) expressed in the World system.
  59735. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59736. * Returns the GroundMesh.
  59737. */
  59738. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59739. var world = this.getWorldMatrix();
  59740. var tmpMat = BABYLON.Tmp.Matrix[5];
  59741. world.invertToRef(tmpMat);
  59742. var tmpVect = BABYLON.Tmp.Vector3[8];
  59743. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59744. x = tmpVect.x;
  59745. z = tmpVect.z;
  59746. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59747. return this;
  59748. }
  59749. if (!this._heightQuads || this._heightQuads.length == 0) {
  59750. this._initHeightQuads();
  59751. this._computeHeightQuads();
  59752. }
  59753. var facet = this._getFacetAt(x, z);
  59754. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59755. return this;
  59756. };
  59757. /**
  59758. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59759. * if the ground has been updated.
  59760. * This can be used in the render loop.
  59761. * Returns the GroundMesh.
  59762. */
  59763. GroundMesh.prototype.updateCoordinateHeights = function () {
  59764. if (!this._heightQuads || this._heightQuads.length == 0) {
  59765. this._initHeightQuads();
  59766. }
  59767. this._computeHeightQuads();
  59768. return this;
  59769. };
  59770. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59771. GroundMesh.prototype._getFacetAt = function (x, z) {
  59772. // retrieve col and row from x, z coordinates in the ground local system
  59773. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59774. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59775. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59776. var facet;
  59777. if (z < quad.slope.x * x + quad.slope.y) {
  59778. facet = quad.facet1;
  59779. }
  59780. else {
  59781. facet = quad.facet2;
  59782. }
  59783. return facet;
  59784. };
  59785. // Creates and populates the heightMap array with "facet" elements :
  59786. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59787. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59788. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59789. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59790. // Returns the GroundMesh.
  59791. GroundMesh.prototype._initHeightQuads = function () {
  59792. var subdivisionsX = this._subdivisionsX;
  59793. var subdivisionsY = this._subdivisionsY;
  59794. this._heightQuads = new Array();
  59795. for (var row = 0; row < subdivisionsY; row++) {
  59796. for (var col = 0; col < subdivisionsX; col++) {
  59797. 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) };
  59798. this._heightQuads[row * subdivisionsX + col] = quad;
  59799. }
  59800. }
  59801. return this;
  59802. };
  59803. // Compute each quad element values and update the the heightMap array :
  59804. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59805. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59806. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59807. // Returns the GroundMesh.
  59808. GroundMesh.prototype._computeHeightQuads = function () {
  59809. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59810. if (!positions) {
  59811. return this;
  59812. }
  59813. var v1 = BABYLON.Tmp.Vector3[3];
  59814. var v2 = BABYLON.Tmp.Vector3[2];
  59815. var v3 = BABYLON.Tmp.Vector3[1];
  59816. var v4 = BABYLON.Tmp.Vector3[0];
  59817. var v1v2 = BABYLON.Tmp.Vector3[4];
  59818. var v1v3 = BABYLON.Tmp.Vector3[5];
  59819. var v1v4 = BABYLON.Tmp.Vector3[6];
  59820. var norm1 = BABYLON.Tmp.Vector3[7];
  59821. var norm2 = BABYLON.Tmp.Vector3[8];
  59822. var i = 0;
  59823. var j = 0;
  59824. var k = 0;
  59825. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59826. var h = 0;
  59827. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59828. var d2 = 0;
  59829. var subdivisionsX = this._subdivisionsX;
  59830. var subdivisionsY = this._subdivisionsY;
  59831. for (var row = 0; row < subdivisionsY; row++) {
  59832. for (var col = 0; col < subdivisionsX; col++) {
  59833. i = col * 3;
  59834. j = row * (subdivisionsX + 1) * 3;
  59835. k = (row + 1) * (subdivisionsX + 1) * 3;
  59836. v1.x = positions[j + i];
  59837. v1.y = positions[j + i + 1];
  59838. v1.z = positions[j + i + 2];
  59839. v2.x = positions[j + i + 3];
  59840. v2.y = positions[j + i + 4];
  59841. v2.z = positions[j + i + 5];
  59842. v3.x = positions[k + i];
  59843. v3.y = positions[k + i + 1];
  59844. v3.z = positions[k + i + 2];
  59845. v4.x = positions[k + i + 3];
  59846. v4.y = positions[k + i + 4];
  59847. v4.z = positions[k + i + 5];
  59848. // 2D slope V1V4
  59849. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59850. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59851. // facet equations :
  59852. // we compute each facet normal vector
  59853. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59854. // we compute the value d by applying the equation to v1 which belongs to the plane
  59855. // then we store the facet equation in a Vector4
  59856. v2.subtractToRef(v1, v1v2);
  59857. v3.subtractToRef(v1, v1v3);
  59858. v4.subtractToRef(v1, v1v4);
  59859. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59860. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59861. norm1.normalize();
  59862. norm2.normalize();
  59863. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59864. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59865. var quad = this._heightQuads[row * subdivisionsX + col];
  59866. quad.slope.copyFromFloats(cd, h);
  59867. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59868. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59869. }
  59870. }
  59871. return this;
  59872. };
  59873. GroundMesh.prototype.serialize = function (serializationObject) {
  59874. _super.prototype.serialize.call(this, serializationObject);
  59875. serializationObject.subdivisionsX = this._subdivisionsX;
  59876. serializationObject.subdivisionsY = this._subdivisionsY;
  59877. serializationObject.minX = this._minX;
  59878. serializationObject.maxX = this._maxX;
  59879. serializationObject.minZ = this._minZ;
  59880. serializationObject.maxZ = this._maxZ;
  59881. serializationObject.width = this._width;
  59882. serializationObject.height = this._height;
  59883. };
  59884. GroundMesh.Parse = function (parsedMesh, scene) {
  59885. var result = new GroundMesh(parsedMesh.name, scene);
  59886. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59887. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59888. result._minX = parsedMesh.minX;
  59889. result._maxX = parsedMesh.maxX;
  59890. result._minZ = parsedMesh.minZ;
  59891. result._maxZ = parsedMesh.maxZ;
  59892. result._width = parsedMesh.width;
  59893. result._height = parsedMesh.height;
  59894. return result;
  59895. };
  59896. return GroundMesh;
  59897. }(BABYLON.Mesh));
  59898. BABYLON.GroundMesh = GroundMesh;
  59899. })(BABYLON || (BABYLON = {}));
  59900. //# sourceMappingURL=babylon.groundMesh.js.map
  59901. var BABYLON;
  59902. (function (BABYLON) {
  59903. /**
  59904. * Creates an instance based on a source mesh.
  59905. */
  59906. var InstancedMesh = /** @class */ (function (_super) {
  59907. __extends(InstancedMesh, _super);
  59908. function InstancedMesh(name, source) {
  59909. var _this = _super.call(this, name, source.getScene()) || this;
  59910. source.instances.push(_this);
  59911. _this._sourceMesh = source;
  59912. _this.position.copyFrom(source.position);
  59913. _this.rotation.copyFrom(source.rotation);
  59914. _this.scaling.copyFrom(source.scaling);
  59915. if (source.rotationQuaternion) {
  59916. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59917. }
  59918. _this.infiniteDistance = source.infiniteDistance;
  59919. _this.setPivotMatrix(source.getPivotMatrix());
  59920. _this.refreshBoundingInfo();
  59921. _this._syncSubMeshes();
  59922. return _this;
  59923. }
  59924. /**
  59925. * Returns the string "InstancedMesh".
  59926. */
  59927. InstancedMesh.prototype.getClassName = function () {
  59928. return "InstancedMesh";
  59929. };
  59930. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59931. // Methods
  59932. get: function () {
  59933. return this._sourceMesh.receiveShadows;
  59934. },
  59935. enumerable: true,
  59936. configurable: true
  59937. });
  59938. Object.defineProperty(InstancedMesh.prototype, "material", {
  59939. get: function () {
  59940. return this._sourceMesh.material;
  59941. },
  59942. enumerable: true,
  59943. configurable: true
  59944. });
  59945. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59946. get: function () {
  59947. return this._sourceMesh.visibility;
  59948. },
  59949. enumerable: true,
  59950. configurable: true
  59951. });
  59952. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59953. get: function () {
  59954. return this._sourceMesh.skeleton;
  59955. },
  59956. enumerable: true,
  59957. configurable: true
  59958. });
  59959. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59960. get: function () {
  59961. return this._sourceMesh.renderingGroupId;
  59962. },
  59963. set: function (value) {
  59964. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59965. return;
  59966. }
  59967. //no-op with warning
  59968. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59969. },
  59970. enumerable: true,
  59971. configurable: true
  59972. });
  59973. /**
  59974. * Returns the total number of vertices (integer).
  59975. */
  59976. InstancedMesh.prototype.getTotalVertices = function () {
  59977. return this._sourceMesh.getTotalVertices();
  59978. };
  59979. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59980. get: function () {
  59981. return this._sourceMesh;
  59982. },
  59983. enumerable: true,
  59984. configurable: true
  59985. });
  59986. /**
  59987. * Is this node ready to be used/rendered
  59988. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59989. * @return {boolean} is it ready
  59990. */
  59991. InstancedMesh.prototype.isReady = function (completeCheck) {
  59992. if (completeCheck === void 0) { completeCheck = false; }
  59993. return this._sourceMesh.isReady(completeCheck, true);
  59994. };
  59995. /**
  59996. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59997. */
  59998. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59999. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60000. };
  60001. /**
  60002. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60003. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60004. * The `data` are either a numeric array either a Float32Array.
  60005. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60006. * 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).
  60007. * Note that a new underlying VertexBuffer object is created each call.
  60008. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60009. *
  60010. * Possible `kind` values :
  60011. * - BABYLON.VertexBuffer.PositionKind
  60012. * - BABYLON.VertexBuffer.UVKind
  60013. * - BABYLON.VertexBuffer.UV2Kind
  60014. * - BABYLON.VertexBuffer.UV3Kind
  60015. * - BABYLON.VertexBuffer.UV4Kind
  60016. * - BABYLON.VertexBuffer.UV5Kind
  60017. * - BABYLON.VertexBuffer.UV6Kind
  60018. * - BABYLON.VertexBuffer.ColorKind
  60019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60023. *
  60024. * Returns the Mesh.
  60025. */
  60026. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60027. if (this.sourceMesh) {
  60028. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60029. }
  60030. return this.sourceMesh;
  60031. };
  60032. /**
  60033. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60034. * If the mesh has no geometry, it is simply returned as it is.
  60035. * The `data` are either a numeric array either a Float32Array.
  60036. * No new underlying VertexBuffer object is created.
  60037. * 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.
  60038. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60039. *
  60040. * Possible `kind` values :
  60041. * - BABYLON.VertexBuffer.PositionKind
  60042. * - BABYLON.VertexBuffer.UVKind
  60043. * - BABYLON.VertexBuffer.UV2Kind
  60044. * - BABYLON.VertexBuffer.UV3Kind
  60045. * - BABYLON.VertexBuffer.UV4Kind
  60046. * - BABYLON.VertexBuffer.UV5Kind
  60047. * - BABYLON.VertexBuffer.UV6Kind
  60048. * - BABYLON.VertexBuffer.ColorKind
  60049. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60050. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60051. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60052. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60053. *
  60054. * Returns the Mesh.
  60055. */
  60056. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60057. if (this.sourceMesh) {
  60058. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60059. }
  60060. return this.sourceMesh;
  60061. };
  60062. /**
  60063. * Sets the mesh indices.
  60064. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60065. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60066. * This method creates a new index buffer each call.
  60067. * Returns the Mesh.
  60068. */
  60069. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60070. if (totalVertices === void 0) { totalVertices = null; }
  60071. if (this.sourceMesh) {
  60072. this.sourceMesh.setIndices(indices, totalVertices);
  60073. }
  60074. return this.sourceMesh;
  60075. };
  60076. /**
  60077. * Boolean : True if the mesh owns the requested kind of data.
  60078. */
  60079. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60080. return this._sourceMesh.isVerticesDataPresent(kind);
  60081. };
  60082. /**
  60083. * Returns an array of indices (IndicesArray).
  60084. */
  60085. InstancedMesh.prototype.getIndices = function () {
  60086. return this._sourceMesh.getIndices();
  60087. };
  60088. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60089. get: function () {
  60090. return this._sourceMesh._positions;
  60091. },
  60092. enumerable: true,
  60093. configurable: true
  60094. });
  60095. /**
  60096. * Sets a new updated BoundingInfo to the mesh.
  60097. * Returns the mesh.
  60098. */
  60099. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60100. var meshBB = this._sourceMesh.getBoundingInfo();
  60101. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60102. this._updateBoundingInfo();
  60103. return this;
  60104. };
  60105. InstancedMesh.prototype._preActivate = function () {
  60106. if (this._currentLOD) {
  60107. this._currentLOD._preActivate();
  60108. }
  60109. return this;
  60110. };
  60111. InstancedMesh.prototype._activate = function (renderId) {
  60112. if (this._currentLOD) {
  60113. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60114. }
  60115. return this;
  60116. };
  60117. /**
  60118. * Returns the current associated LOD AbstractMesh.
  60119. */
  60120. InstancedMesh.prototype.getLOD = function (camera) {
  60121. if (!camera) {
  60122. return this;
  60123. }
  60124. var boundingInfo = this.getBoundingInfo();
  60125. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60126. if (this._currentLOD === this.sourceMesh) {
  60127. return this;
  60128. }
  60129. return this._currentLOD;
  60130. };
  60131. InstancedMesh.prototype._syncSubMeshes = function () {
  60132. this.releaseSubMeshes();
  60133. if (this._sourceMesh.subMeshes) {
  60134. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60135. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60136. }
  60137. }
  60138. return this;
  60139. };
  60140. InstancedMesh.prototype._generatePointsArray = function () {
  60141. return this._sourceMesh._generatePointsArray();
  60142. };
  60143. /**
  60144. * Creates a new InstancedMesh from the current mesh.
  60145. * - name (string) : the cloned mesh name
  60146. * - newParent (optional Node) : the optional Node to parent the clone to.
  60147. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60148. *
  60149. * Returns the clone.
  60150. */
  60151. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60152. var result = this._sourceMesh.createInstance(name);
  60153. // Deep copy
  60154. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60155. // Bounding info
  60156. this.refreshBoundingInfo();
  60157. // Parent
  60158. if (newParent) {
  60159. result.parent = newParent;
  60160. }
  60161. if (!doNotCloneChildren) {
  60162. // Children
  60163. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60164. var mesh = this.getScene().meshes[index];
  60165. if (mesh.parent === this) {
  60166. mesh.clone(mesh.name, result);
  60167. }
  60168. }
  60169. }
  60170. result.computeWorldMatrix(true);
  60171. return result;
  60172. };
  60173. /**
  60174. * Disposes the InstancedMesh.
  60175. * Returns nothing.
  60176. */
  60177. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60178. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60179. // Remove from mesh
  60180. var index = this._sourceMesh.instances.indexOf(this);
  60181. this._sourceMesh.instances.splice(index, 1);
  60182. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60183. };
  60184. return InstancedMesh;
  60185. }(BABYLON.AbstractMesh));
  60186. BABYLON.InstancedMesh = InstancedMesh;
  60187. })(BABYLON || (BABYLON = {}));
  60188. //# sourceMappingURL=babylon.instancedMesh.js.map
  60189. var BABYLON;
  60190. (function (BABYLON) {
  60191. var LinesMesh = /** @class */ (function (_super) {
  60192. __extends(LinesMesh, _super);
  60193. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60194. if (scene === void 0) { scene = null; }
  60195. if (parent === void 0) { parent = null; }
  60196. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60197. _this.useVertexColor = useVertexColor;
  60198. _this.useVertexAlpha = useVertexAlpha;
  60199. _this.color = new BABYLON.Color3(1, 1, 1);
  60200. _this.alpha = 1;
  60201. if (source) {
  60202. _this.color = source.color.clone();
  60203. _this.alpha = source.alpha;
  60204. _this.useVertexColor = source.useVertexColor;
  60205. _this.useVertexAlpha = source.useVertexAlpha;
  60206. }
  60207. _this._intersectionThreshold = 0.1;
  60208. var defines = [];
  60209. var options = {
  60210. attributes: [BABYLON.VertexBuffer.PositionKind],
  60211. uniforms: ["world", "viewProjection"],
  60212. needAlphaBlending: true,
  60213. defines: defines
  60214. };
  60215. if (useVertexAlpha === false) {
  60216. options.needAlphaBlending = false;
  60217. }
  60218. if (!useVertexColor) {
  60219. options.uniforms.push("color");
  60220. }
  60221. else {
  60222. options.defines.push("#define VERTEXCOLOR");
  60223. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60224. }
  60225. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60226. return _this;
  60227. }
  60228. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60229. /**
  60230. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60231. * This margin is expressed in world space coordinates, so its value may vary.
  60232. * Default value is 0.1
  60233. * @returns the intersection Threshold value.
  60234. */
  60235. get: function () {
  60236. return this._intersectionThreshold;
  60237. },
  60238. /**
  60239. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60240. * This margin is expressed in world space coordinates, so its value may vary.
  60241. * @param value the new threshold to apply
  60242. */
  60243. set: function (value) {
  60244. if (this._intersectionThreshold === value) {
  60245. return;
  60246. }
  60247. this._intersectionThreshold = value;
  60248. if (this.geometry) {
  60249. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60250. }
  60251. },
  60252. enumerable: true,
  60253. configurable: true
  60254. });
  60255. /**
  60256. * Returns the string "LineMesh"
  60257. */
  60258. LinesMesh.prototype.getClassName = function () {
  60259. return "LinesMesh";
  60260. };
  60261. Object.defineProperty(LinesMesh.prototype, "material", {
  60262. get: function () {
  60263. return this._colorShader;
  60264. },
  60265. set: function (value) {
  60266. // Do nothing
  60267. },
  60268. enumerable: true,
  60269. configurable: true
  60270. });
  60271. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60272. get: function () {
  60273. return false;
  60274. },
  60275. enumerable: true,
  60276. configurable: true
  60277. });
  60278. LinesMesh.prototype.createInstance = function (name) {
  60279. throw new Error("LinesMeshes do not support createInstance.");
  60280. };
  60281. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60282. if (!this._geometry) {
  60283. return this;
  60284. }
  60285. // VBOs
  60286. this._geometry._bind(this._colorShader.getEffect());
  60287. // Color
  60288. if (!this.useVertexColor) {
  60289. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60290. }
  60291. return this;
  60292. };
  60293. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60294. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60295. return this;
  60296. }
  60297. var engine = this.getScene().getEngine();
  60298. // Draw order
  60299. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60300. return this;
  60301. };
  60302. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60303. this._colorShader.dispose();
  60304. _super.prototype.dispose.call(this, doNotRecurse);
  60305. };
  60306. /**
  60307. * Returns a new LineMesh object cloned from the current one.
  60308. */
  60309. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60310. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60311. };
  60312. return LinesMesh;
  60313. }(BABYLON.Mesh));
  60314. BABYLON.LinesMesh = LinesMesh;
  60315. })(BABYLON || (BABYLON = {}));
  60316. //# sourceMappingURL=babylon.linesMesh.js.map
  60317. var BABYLON;
  60318. (function (BABYLON) {
  60319. /**
  60320. * Class containing static functions to help procedurally build meshes
  60321. */
  60322. var MeshBuilder = /** @class */ (function () {
  60323. function MeshBuilder() {
  60324. }
  60325. MeshBuilder.updateSideOrientation = function (orientation) {
  60326. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60327. return BABYLON.Mesh.DOUBLESIDE;
  60328. }
  60329. if (orientation === undefined || orientation === null) {
  60330. return BABYLON.Mesh.FRONTSIDE;
  60331. }
  60332. return orientation;
  60333. };
  60334. /**
  60335. * Creates a box mesh
  60336. * * The parameter `size` sets the size (float) of each box side (default 1)
  60337. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60338. * * 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)
  60339. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60340. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60341. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60342. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60343. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60344. * @param name defines the name of the mesh
  60345. * @param options defines the options used to create the mesh
  60346. * @param scene defines the hosting scene
  60347. * @returns the box mesh
  60348. */
  60349. MeshBuilder.CreateBox = function (name, options, scene) {
  60350. if (scene === void 0) { scene = null; }
  60351. var box = new BABYLON.Mesh(name, scene);
  60352. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60353. box._originalBuilderSideOrientation = options.sideOrientation;
  60354. var vertexData = BABYLON.VertexData.CreateBox(options);
  60355. vertexData.applyToMesh(box, options.updatable);
  60356. return box;
  60357. };
  60358. /**
  60359. * Creates a sphere mesh
  60360. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60361. * * 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 than `diameter`)
  60362. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60363. * * 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
  60364. * * 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)
  60365. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60366. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60367. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60368. * @param name defines the name of the mesh
  60369. * @param options defines the options used to create the mesh
  60370. * @param scene defines the hosting scene
  60371. * @returns the sphere mesh
  60372. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60373. */
  60374. MeshBuilder.CreateSphere = function (name, options, scene) {
  60375. var sphere = new BABYLON.Mesh(name, scene);
  60376. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60377. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60378. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60379. vertexData.applyToMesh(sphere, options.updatable);
  60380. return sphere;
  60381. };
  60382. /**
  60383. * Creates a plane polygonal mesh. By default, this is a disc
  60384. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60385. * * 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
  60386. * * 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
  60387. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60388. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60389. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60390. * @param name defines the name of the mesh
  60391. * @param options defines the options used to create the mesh
  60392. * @param scene defines the hosting scene
  60393. * @returns the plane polygonal mesh
  60394. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60395. */
  60396. MeshBuilder.CreateDisc = function (name, options, scene) {
  60397. if (scene === void 0) { scene = null; }
  60398. var disc = new BABYLON.Mesh(name, scene);
  60399. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60400. disc._originalBuilderSideOrientation = options.sideOrientation;
  60401. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60402. vertexData.applyToMesh(disc, options.updatable);
  60403. return disc;
  60404. };
  60405. /**
  60406. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60407. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60408. * * 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`)
  60409. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60410. * * 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
  60411. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60412. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60413. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60414. * @param name defines the name of the mesh
  60415. * @param options defines the options used to create the mesh
  60416. * @param scene defines the hosting scene
  60417. * @returns the icosahedron mesh
  60418. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60419. */
  60420. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60421. var sphere = new BABYLON.Mesh(name, scene);
  60422. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60423. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60424. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60425. vertexData.applyToMesh(sphere, options.updatable);
  60426. return sphere;
  60427. };
  60428. ;
  60429. /**
  60430. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60431. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60432. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60433. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60434. * * 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
  60435. * * 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
  60436. * * 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
  60437. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60438. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60439. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60440. * * 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
  60441. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60442. * * 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
  60443. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60444. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60445. * @param name defines the name of the mesh
  60446. * @param options defines the options used to create the mesh
  60447. * @param scene defines the hosting scene
  60448. * @returns the ribbon mesh
  60449. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60450. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60451. */
  60452. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60453. if (scene === void 0) { scene = null; }
  60454. var pathArray = options.pathArray;
  60455. var closeArray = options.closeArray;
  60456. var closePath = options.closePath;
  60457. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60458. var instance = options.instance;
  60459. var updatable = options.updatable;
  60460. if (instance) { // existing ribbon instance update
  60461. // positionFunction : ribbon case
  60462. // only pathArray and sideOrientation parameters are taken into account for positions update
  60463. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60464. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60465. var positionFunction = function (positions) {
  60466. var minlg = pathArray[0].length;
  60467. var i = 0;
  60468. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60469. for (var si = 1; si <= ns; si++) {
  60470. for (var p = 0; p < pathArray.length; p++) {
  60471. var path = pathArray[p];
  60472. var l = path.length;
  60473. minlg = (minlg < l) ? minlg : l;
  60474. var j = 0;
  60475. while (j < minlg) {
  60476. positions[i] = path[j].x;
  60477. positions[i + 1] = path[j].y;
  60478. positions[i + 2] = path[j].z;
  60479. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60480. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60481. }
  60482. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60483. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60484. }
  60485. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60486. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60487. }
  60488. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60489. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60490. }
  60491. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60492. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60493. }
  60494. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60495. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60496. }
  60497. j++;
  60498. i += 3;
  60499. }
  60500. if (instance._closePath) {
  60501. positions[i] = path[0].x;
  60502. positions[i + 1] = path[0].y;
  60503. positions[i + 2] = path[0].z;
  60504. i += 3;
  60505. }
  60506. }
  60507. }
  60508. };
  60509. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60510. positionFunction(positions);
  60511. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60512. instance._boundingInfo.update(instance._worldMatrix);
  60513. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60514. if (options.colors) {
  60515. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60516. for (var c = 0; c < options.colors.length; c++) {
  60517. colors[c * 4] = options.colors[c].r;
  60518. colors[c * 4 + 1] = options.colors[c].g;
  60519. colors[c * 4 + 2] = options.colors[c].b;
  60520. colors[c * 4 + 3] = options.colors[c].a;
  60521. }
  60522. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60523. }
  60524. if (options.uvs) {
  60525. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60526. for (var i = 0; i < options.uvs.length; i++) {
  60527. uvs[i * 2] = options.uvs[i].x;
  60528. uvs[i * 2 + 1] = options.uvs[i].y;
  60529. }
  60530. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60531. }
  60532. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60533. var indices = instance.getIndices();
  60534. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60535. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60536. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60537. if (instance._closePath) {
  60538. var indexFirst = 0;
  60539. var indexLast = 0;
  60540. for (var p = 0; p < pathArray.length; p++) {
  60541. indexFirst = instance._idx[p] * 3;
  60542. if (p + 1 < pathArray.length) {
  60543. indexLast = (instance._idx[p + 1] - 1) * 3;
  60544. }
  60545. else {
  60546. indexLast = normals.length - 3;
  60547. }
  60548. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60549. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60550. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60551. normals[indexLast] = normals[indexFirst];
  60552. normals[indexLast + 1] = normals[indexFirst + 1];
  60553. normals[indexLast + 2] = normals[indexFirst + 2];
  60554. }
  60555. }
  60556. if (!(instance.areNormalsFrozen)) {
  60557. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60558. }
  60559. }
  60560. return instance;
  60561. }
  60562. else { // new ribbon creation
  60563. var ribbon = new BABYLON.Mesh(name, scene);
  60564. ribbon._originalBuilderSideOrientation = sideOrientation;
  60565. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60566. if (closePath) {
  60567. ribbon._idx = vertexData._idx;
  60568. }
  60569. ribbon._closePath = closePath;
  60570. ribbon._closeArray = closeArray;
  60571. vertexData.applyToMesh(ribbon, updatable);
  60572. return ribbon;
  60573. }
  60574. };
  60575. /**
  60576. * Creates a cylinder or a cone mesh
  60577. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60578. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60579. * * 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.
  60580. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60581. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60582. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60583. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60584. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60585. * * 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).
  60586. * * 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
  60587. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60588. * * 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
  60589. * * 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.
  60590. * * If `enclose` is false, a ring surface is one element.
  60591. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60592. * * 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
  60593. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60594. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60595. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60596. * @param name defines the name of the mesh
  60597. * @param options defines the options used to create the mesh
  60598. * @param scene defines the hosting scene
  60599. * @returns the cylinder mesh
  60600. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60601. */
  60602. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60603. var cylinder = new BABYLON.Mesh(name, scene);
  60604. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60605. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60606. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60607. vertexData.applyToMesh(cylinder, options.updatable);
  60608. return cylinder;
  60609. };
  60610. /**
  60611. * Creates a torus mesh
  60612. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60613. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60614. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60615. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60616. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60617. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60618. * @param name defines the name of the mesh
  60619. * @param options defines the options used to create the mesh
  60620. * @param scene defines the hosting scene
  60621. * @returns the torus mesh
  60622. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60623. */
  60624. MeshBuilder.CreateTorus = function (name, options, scene) {
  60625. var torus = new BABYLON.Mesh(name, scene);
  60626. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60627. torus._originalBuilderSideOrientation = options.sideOrientation;
  60628. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60629. vertexData.applyToMesh(torus, options.updatable);
  60630. return torus;
  60631. };
  60632. /**
  60633. * Creates a torus knot mesh
  60634. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60635. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60636. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60637. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60638. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60639. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60641. * @param name defines the name of the mesh
  60642. * @param options defines the options used to create the mesh
  60643. * @param scene defines the hosting scene
  60644. * @returns the torus knot mesh
  60645. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60646. */
  60647. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60648. var torusKnot = new BABYLON.Mesh(name, scene);
  60649. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60650. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60651. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60652. vertexData.applyToMesh(torusKnot, options.updatable);
  60653. return torusKnot;
  60654. };
  60655. /**
  60656. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60657. * * 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
  60658. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60659. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60660. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60661. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60662. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60663. * * 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
  60664. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60665. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60666. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60667. * @param name defines the name of the new line system
  60668. * @param options defines the options used to create the line system
  60669. * @param scene defines the hosting scene
  60670. * @returns a new line system mesh
  60671. */
  60672. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60673. var instance = options.instance;
  60674. var lines = options.lines;
  60675. var colors = options.colors;
  60676. if (instance) { // lines update
  60677. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60678. var vertexColor;
  60679. var lineColors;
  60680. if (colors) {
  60681. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60682. }
  60683. var i = 0;
  60684. var c = 0;
  60685. for (var l = 0; l < lines.length; l++) {
  60686. var points = lines[l];
  60687. for (var p = 0; p < points.length; p++) {
  60688. positions[i] = points[p].x;
  60689. positions[i + 1] = points[p].y;
  60690. positions[i + 2] = points[p].z;
  60691. if (colors && vertexColor) {
  60692. lineColors = colors[l];
  60693. vertexColor[c] = lineColors[p].r;
  60694. vertexColor[c + 1] = lineColors[p].g;
  60695. vertexColor[c + 2] = lineColors[p].b;
  60696. vertexColor[c + 3] = lineColors[p].a;
  60697. c += 4;
  60698. }
  60699. i += 3;
  60700. }
  60701. }
  60702. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60703. if (colors && vertexColor) {
  60704. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60705. }
  60706. return instance;
  60707. }
  60708. // line system creation
  60709. var useVertexColor = (colors) ? true : false;
  60710. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60711. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60712. vertexData.applyToMesh(lineSystem, options.updatable);
  60713. return lineSystem;
  60714. };
  60715. /**
  60716. * Creates a line mesh
  60717. * 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
  60718. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60719. * * The parameter `points` is an array successive Vector3
  60720. * * 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
  60721. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60722. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60723. * * When updating an instance, remember that only point positions can change, not the number of points
  60724. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60725. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60726. * @param name defines the name of the new line system
  60727. * @param options defines the options used to create the line system
  60728. * @param scene defines the hosting scene
  60729. * @returns a new line mesh
  60730. */
  60731. MeshBuilder.CreateLines = function (name, options, scene) {
  60732. if (scene === void 0) { scene = null; }
  60733. var colors = (options.colors) ? [options.colors] : null;
  60734. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60735. return lines;
  60736. };
  60737. /**
  60738. * Creates a dashed line mesh
  60739. * * 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
  60740. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60741. * * The parameter `points` is an array successive Vector3
  60742. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60743. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60744. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60745. * * 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
  60746. * * When updating an instance, remember that only point positions can change, not the number of points
  60747. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60748. * @param name defines the name of the mesh
  60749. * @param options defines the options used to create the mesh
  60750. * @param scene defines the hosting scene
  60751. * @returns the dashed line mesh
  60752. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60753. */
  60754. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60755. if (scene === void 0) { scene = null; }
  60756. var points = options.points;
  60757. var instance = options.instance;
  60758. var gapSize = options.gapSize || 1;
  60759. var dashSize = options.dashSize || 3;
  60760. if (instance) { // dashed lines update
  60761. var positionFunction = function (positions) {
  60762. var curvect = BABYLON.Vector3.Zero();
  60763. var nbSeg = positions.length / 6;
  60764. var lg = 0;
  60765. var nb = 0;
  60766. var shft = 0;
  60767. var dashshft = 0;
  60768. var curshft = 0;
  60769. var p = 0;
  60770. var i = 0;
  60771. var j = 0;
  60772. for (i = 0; i < points.length - 1; i++) {
  60773. points[i + 1].subtractToRef(points[i], curvect);
  60774. lg += curvect.length();
  60775. }
  60776. shft = lg / nbSeg;
  60777. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60778. for (i = 0; i < points.length - 1; i++) {
  60779. points[i + 1].subtractToRef(points[i], curvect);
  60780. nb = Math.floor(curvect.length() / shft);
  60781. curvect.normalize();
  60782. j = 0;
  60783. while (j < nb && p < positions.length) {
  60784. curshft = shft * j;
  60785. positions[p] = points[i].x + curshft * curvect.x;
  60786. positions[p + 1] = points[i].y + curshft * curvect.y;
  60787. positions[p + 2] = points[i].z + curshft * curvect.z;
  60788. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60789. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60790. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60791. p += 6;
  60792. j++;
  60793. }
  60794. }
  60795. while (p < positions.length) {
  60796. positions[p] = points[i].x;
  60797. positions[p + 1] = points[i].y;
  60798. positions[p + 2] = points[i].z;
  60799. p += 3;
  60800. }
  60801. };
  60802. instance.updateMeshPositions(positionFunction, false);
  60803. return instance;
  60804. }
  60805. // dashed lines creation
  60806. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60807. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60808. vertexData.applyToMesh(dashedLines, options.updatable);
  60809. dashedLines.dashSize = dashSize;
  60810. dashedLines.gapSize = gapSize;
  60811. return dashedLines;
  60812. };
  60813. /**
  60814. * 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.
  60815. * * 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.
  60816. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60817. * * 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.
  60818. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60819. * * 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
  60820. * * 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
  60821. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60822. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60823. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60824. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60826. * @param name defines the name of the mesh
  60827. * @param options defines the options used to create the mesh
  60828. * @param scene defines the hosting scene
  60829. * @returns the extruded shape mesh
  60830. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60831. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60832. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60833. */
  60834. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60835. if (scene === void 0) { scene = null; }
  60836. var path = options.path;
  60837. var shape = options.shape;
  60838. var scale = options.scale || 1;
  60839. var rotation = options.rotation || 0;
  60840. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60841. var updatable = options.updatable;
  60842. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60843. var instance = options.instance || null;
  60844. var invertUV = options.invertUV || false;
  60845. 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);
  60846. };
  60847. /**
  60848. * Creates an custom extruded shape mesh.
  60849. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60850. * * 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.
  60851. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60852. * * 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
  60853. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60854. * * 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
  60855. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60856. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60857. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60858. * * 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
  60859. * * 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
  60860. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60861. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60862. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60863. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60864. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60865. * @param name defines the name of the mesh
  60866. * @param options defines the options used to create the mesh
  60867. * @param scene defines the hosting scene
  60868. * @returns the custom extruded shape mesh
  60869. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60870. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60871. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60872. */
  60873. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60874. var path = options.path;
  60875. var shape = options.shape;
  60876. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60877. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60878. var ribbonCloseArray = options.ribbonCloseArray || false;
  60879. var ribbonClosePath = options.ribbonClosePath || false;
  60880. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60881. var updatable = options.updatable;
  60882. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60883. var instance = options.instance;
  60884. var invertUV = options.invertUV || false;
  60885. 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);
  60886. };
  60887. /**
  60888. * Creates lathe mesh.
  60889. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60890. * * 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
  60891. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60892. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60893. * * 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
  60894. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60895. * * 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
  60896. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60897. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60898. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60899. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60900. * @param name defines the name of the mesh
  60901. * @param options defines the options used to create the mesh
  60902. * @param scene defines the hosting scene
  60903. * @returns the lathe mesh
  60904. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60905. */
  60906. MeshBuilder.CreateLathe = function (name, options, scene) {
  60907. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60908. var closed = (options.closed === undefined) ? true : options.closed;
  60909. var shape = options.shape;
  60910. var radius = options.radius || 1;
  60911. var tessellation = options.tessellation || 64;
  60912. var updatable = options.updatable;
  60913. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60914. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60915. var pi2 = Math.PI * 2;
  60916. var paths = new Array();
  60917. var invertUV = options.invertUV || false;
  60918. var i = 0;
  60919. var p = 0;
  60920. var step = pi2 / tessellation * arc;
  60921. var rotated;
  60922. var path = new Array();
  60923. ;
  60924. for (i = 0; i <= tessellation; i++) {
  60925. var path = [];
  60926. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60927. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60928. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60929. }
  60930. for (p = 0; p < shape.length; p++) {
  60931. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60932. path.push(rotated);
  60933. }
  60934. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60935. 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));
  60936. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60937. }
  60938. paths.push(path);
  60939. }
  60940. // lathe ribbon
  60941. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60942. return lathe;
  60943. };
  60944. /**
  60945. * Creates a plane mesh
  60946. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60947. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60948. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60949. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60950. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60951. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60952. * @param name defines the name of the mesh
  60953. * @param options defines the options used to create the mesh
  60954. * @param scene defines the hosting scene
  60955. * @returns the plane mesh
  60956. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60957. */
  60958. MeshBuilder.CreatePlane = function (name, options, scene) {
  60959. var plane = new BABYLON.Mesh(name, scene);
  60960. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60961. plane._originalBuilderSideOrientation = options.sideOrientation;
  60962. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60963. vertexData.applyToMesh(plane, options.updatable);
  60964. if (options.sourcePlane) {
  60965. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60966. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60967. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60968. plane.rotate(vectorProduct, product);
  60969. }
  60970. return plane;
  60971. };
  60972. /**
  60973. * Creates a ground mesh
  60974. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60975. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60976. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60977. * @param name defines the name of the mesh
  60978. * @param options defines the options used to create the mesh
  60979. * @param scene defines the hosting scene
  60980. * @returns the ground mesh
  60981. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60982. */
  60983. MeshBuilder.CreateGround = function (name, options, scene) {
  60984. var ground = new BABYLON.GroundMesh(name, scene);
  60985. ground._setReady(false);
  60986. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60987. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60988. ground._width = options.width || 1;
  60989. ground._height = options.height || 1;
  60990. ground._maxX = ground._width / 2;
  60991. ground._maxZ = ground._height / 2;
  60992. ground._minX = -ground._maxX;
  60993. ground._minZ = -ground._maxZ;
  60994. var vertexData = BABYLON.VertexData.CreateGround(options);
  60995. vertexData.applyToMesh(ground, options.updatable);
  60996. ground._setReady(true);
  60997. return ground;
  60998. };
  60999. /**
  61000. * Creates a tiled ground mesh
  61001. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61002. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61003. * * 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
  61004. * * 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
  61005. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61006. * @param name defines the name of the mesh
  61007. * @param options defines the options used to create the mesh
  61008. * @param scene defines the hosting scene
  61009. * @returns the tiled ground mesh
  61010. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61011. */
  61012. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61013. var tiledGround = new BABYLON.Mesh(name, scene);
  61014. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61015. vertexData.applyToMesh(tiledGround, options.updatable);
  61016. return tiledGround;
  61017. };
  61018. /**
  61019. * Creates a ground mesh from a height map
  61020. * * The parameter `url` sets the URL of the height map image resource.
  61021. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61022. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61023. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61024. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61025. * * 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.
  61026. * * 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).
  61027. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61028. * @param name defines the name of the mesh
  61029. * @param url defines the url to the height map
  61030. * @param options defines the options used to create the mesh
  61031. * @param scene defines the hosting scene
  61032. * @returns the ground mesh
  61033. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  61034. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61035. */
  61036. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61037. var width = options.width || 10.0;
  61038. var height = options.height || 10.0;
  61039. var subdivisions = options.subdivisions || 1 | 0;
  61040. var minHeight = options.minHeight || 0.0;
  61041. var maxHeight = options.maxHeight || 1.0;
  61042. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61043. var updatable = options.updatable;
  61044. var onReady = options.onReady;
  61045. var ground = new BABYLON.GroundMesh(name, scene);
  61046. ground._subdivisionsX = subdivisions;
  61047. ground._subdivisionsY = subdivisions;
  61048. ground._width = width;
  61049. ground._height = height;
  61050. ground._maxX = ground._width / 2.0;
  61051. ground._maxZ = ground._height / 2.0;
  61052. ground._minX = -ground._maxX;
  61053. ground._minZ = -ground._maxZ;
  61054. ground._setReady(false);
  61055. var onload = function (img) {
  61056. // Getting height map data
  61057. var canvas = document.createElement("canvas");
  61058. var context = canvas.getContext("2d");
  61059. if (!context) {
  61060. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61061. }
  61062. if (scene.isDisposed) {
  61063. return;
  61064. }
  61065. var bufferWidth = img.width;
  61066. var bufferHeight = img.height;
  61067. canvas.width = bufferWidth;
  61068. canvas.height = bufferHeight;
  61069. context.drawImage(img, 0, 0);
  61070. // Create VertexData from map data
  61071. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61072. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61073. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61074. width: width, height: height,
  61075. subdivisions: subdivisions,
  61076. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61077. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61078. });
  61079. vertexData.applyToMesh(ground, updatable);
  61080. //execute ready callback, if set
  61081. if (onReady) {
  61082. onReady(ground);
  61083. }
  61084. ground._setReady(true);
  61085. };
  61086. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61087. return ground;
  61088. };
  61089. /**
  61090. * Creates a polygon mesh
  61091. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61092. * * 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
  61093. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61094. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61095. * * 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)
  61096. * * Remember you can only change the shape positions, not their number when updating a polygon
  61097. * @param name defines the name of the mesh
  61098. * @param options defines the options used to create the mesh
  61099. * @param scene defines the hosting scene
  61100. * @returns the polygon mesh
  61101. */
  61102. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61103. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61104. var shape = options.shape;
  61105. var holes = options.holes || [];
  61106. var depth = options.depth || 0;
  61107. var contours = [];
  61108. var hole = [];
  61109. for (var i = 0; i < shape.length; i++) {
  61110. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61111. }
  61112. var epsilon = 0.00000001;
  61113. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61114. contours.pop();
  61115. }
  61116. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61117. for (var hNb = 0; hNb < holes.length; hNb++) {
  61118. hole = [];
  61119. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61120. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61121. }
  61122. polygonTriangulation.addHole(hole);
  61123. }
  61124. var polygon = polygonTriangulation.build(options.updatable, depth);
  61125. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61126. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61127. vertexData.applyToMesh(polygon, options.updatable);
  61128. return polygon;
  61129. };
  61130. ;
  61131. /**
  61132. * Creates an extruded polygon mesh, with depth in the Y direction.
  61133. * * 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)
  61134. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61135. * @param name defines the name of the mesh
  61136. * @param options defines the options used to create the mesh
  61137. * @param scene defines the hosting scene
  61138. * @returns the polygon mesh
  61139. */
  61140. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61141. return MeshBuilder.CreatePolygon(name, options, scene);
  61142. };
  61143. ;
  61144. /**
  61145. * Creates a tube mesh.
  61146. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61147. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61148. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61149. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61150. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61151. * * 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)
  61152. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61153. * * 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
  61154. * * 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
  61155. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61156. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  61157. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61158. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61159. * @param name defines the name of the mesh
  61160. * @param options defines the options used to create the mesh
  61161. * @param scene defines the hosting scene
  61162. * @returns the tube mesh
  61163. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61164. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61165. */
  61166. MeshBuilder.CreateTube = function (name, options, scene) {
  61167. var path = options.path;
  61168. var instance = options.instance;
  61169. var radius = 1.0;
  61170. if (instance) {
  61171. radius = instance.radius;
  61172. }
  61173. if (options.radius !== undefined) {
  61174. radius = options.radius;
  61175. }
  61176. ;
  61177. var tessellation = options.tessellation || 64 | 0;
  61178. var radiusFunction = options.radiusFunction || null;
  61179. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61180. var invertUV = options.invertUV || false;
  61181. var updatable = options.updatable;
  61182. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61183. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61184. // tube geometry
  61185. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61186. var tangents = path3D.getTangents();
  61187. var normals = path3D.getNormals();
  61188. var distances = path3D.getDistances();
  61189. var pi2 = Math.PI * 2;
  61190. var step = pi2 / tessellation * arc;
  61191. var returnRadius = function () { return radius; };
  61192. var radiusFunctionFinal = radiusFunction || returnRadius;
  61193. var circlePath;
  61194. var rad;
  61195. var normal;
  61196. var rotated;
  61197. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61198. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61199. for (var i = 0; i < path.length; i++) {
  61200. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61201. circlePath = Array(); // current circle array
  61202. normal = normals[i]; // current normal
  61203. for (var t = 0; t < tessellation; t++) {
  61204. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61205. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61206. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61207. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61208. circlePath[t] = rotated;
  61209. }
  61210. circlePaths[index] = circlePath;
  61211. index++;
  61212. }
  61213. // cap
  61214. var capPath = function (nbPoints, pathIndex) {
  61215. var pointCap = Array();
  61216. for (var i = 0; i < nbPoints; i++) {
  61217. pointCap.push(path[pathIndex]);
  61218. }
  61219. return pointCap;
  61220. };
  61221. switch (cap) {
  61222. case BABYLON.Mesh.NO_CAP:
  61223. break;
  61224. case BABYLON.Mesh.CAP_START:
  61225. circlePaths[0] = capPath(tessellation, 0);
  61226. circlePaths[1] = circlePaths[2].slice(0);
  61227. break;
  61228. case BABYLON.Mesh.CAP_END:
  61229. circlePaths[index] = circlePaths[index - 1].slice(0);
  61230. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61231. break;
  61232. case BABYLON.Mesh.CAP_ALL:
  61233. circlePaths[0] = capPath(tessellation, 0);
  61234. circlePaths[1] = circlePaths[2].slice(0);
  61235. circlePaths[index] = circlePaths[index - 1].slice(0);
  61236. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61237. break;
  61238. default:
  61239. break;
  61240. }
  61241. return circlePaths;
  61242. };
  61243. var path3D;
  61244. var pathArray;
  61245. if (instance) { // tube update
  61246. var arc = options.arc || instance.arc;
  61247. path3D = (instance.path3D).update(path);
  61248. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61249. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61250. instance.path3D = path3D;
  61251. instance.pathArray = pathArray;
  61252. instance.arc = arc;
  61253. instance.radius = radius;
  61254. return instance;
  61255. }
  61256. // tube creation
  61257. path3D = new BABYLON.Path3D(path);
  61258. var newPathArray = new Array();
  61259. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61260. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61261. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61262. tube.pathArray = pathArray;
  61263. tube.path3D = path3D;
  61264. tube.tessellation = tessellation;
  61265. tube.cap = cap;
  61266. tube.arc = options.arc;
  61267. tube.radius = radius;
  61268. return tube;
  61269. };
  61270. /**
  61271. * Creates a polyhedron mesh
  61272. * * 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
  61273. * * The parameter `size` (positive float, default 1) sets the polygon size
  61274. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61275. * * 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`
  61276. * * 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
  61277. * * 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)`)
  61278. * * 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
  61279. * * 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
  61280. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61281. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  61282. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61283. * @param name defines the name of the mesh
  61284. * @param options defines the options used to create the mesh
  61285. * @param scene defines the hosting scene
  61286. * @returns the polyhedron mesh
  61287. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  61288. */
  61289. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61290. var polyhedron = new BABYLON.Mesh(name, scene);
  61291. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61292. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61293. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61294. vertexData.applyToMesh(polyhedron, options.updatable);
  61295. return polyhedron;
  61296. };
  61297. /**
  61298. * Creates a decal mesh.
  61299. * 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
  61300. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61301. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61302. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61303. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61304. * @param name defines the name of the mesh
  61305. * @param sourceMesh defines the mesh where the decal must be applied
  61306. * @param options defines the options used to create the mesh
  61307. * @param scene defines the hosting scene
  61308. * @returns the decal mesh
  61309. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  61310. */
  61311. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61312. var indices = sourceMesh.getIndices();
  61313. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61314. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61315. var position = options.position || BABYLON.Vector3.Zero();
  61316. var normal = options.normal || BABYLON.Vector3.Up();
  61317. var size = options.size || BABYLON.Vector3.One();
  61318. var angle = options.angle || 0;
  61319. // Getting correct rotation
  61320. if (!normal) {
  61321. var target = new BABYLON.Vector3(0, 0, 1);
  61322. var camera = sourceMesh.getScene().activeCamera;
  61323. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61324. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61325. }
  61326. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61327. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61328. var pitch = Math.atan2(normal.y, len);
  61329. // Matrix
  61330. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61331. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61332. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61333. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61334. var vertexData = new BABYLON.VertexData();
  61335. vertexData.indices = [];
  61336. vertexData.positions = [];
  61337. vertexData.normals = [];
  61338. vertexData.uvs = [];
  61339. var currentVertexDataIndex = 0;
  61340. var extractDecalVector3 = function (indexId) {
  61341. var result = new BABYLON.PositionNormalVertex();
  61342. if (!indices || !positions || !normals) {
  61343. return result;
  61344. }
  61345. var vertexId = indices[indexId];
  61346. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61347. // Send vector to decal local world
  61348. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61349. // Get normal
  61350. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61351. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61352. return result;
  61353. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61354. var clip = function (vertices, axis) {
  61355. if (vertices.length === 0) {
  61356. return vertices;
  61357. }
  61358. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61359. var clipVertices = function (v0, v1) {
  61360. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61361. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61362. };
  61363. var result = new Array();
  61364. for (var index = 0; index < vertices.length; index += 3) {
  61365. var v1Out;
  61366. var v2Out;
  61367. var v3Out;
  61368. var total = 0;
  61369. var nV1 = null;
  61370. var nV2 = null;
  61371. var nV3 = null;
  61372. var nV4 = null;
  61373. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61374. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61375. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61376. v1Out = d1 > 0;
  61377. v2Out = d2 > 0;
  61378. v3Out = d3 > 0;
  61379. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61380. switch (total) {
  61381. case 0:
  61382. result.push(vertices[index]);
  61383. result.push(vertices[index + 1]);
  61384. result.push(vertices[index + 2]);
  61385. break;
  61386. case 1:
  61387. if (v1Out) {
  61388. nV1 = vertices[index + 1];
  61389. nV2 = vertices[index + 2];
  61390. nV3 = clipVertices(vertices[index], nV1);
  61391. nV4 = clipVertices(vertices[index], nV2);
  61392. }
  61393. if (v2Out) {
  61394. nV1 = vertices[index];
  61395. nV2 = vertices[index + 2];
  61396. nV3 = clipVertices(vertices[index + 1], nV1);
  61397. nV4 = clipVertices(vertices[index + 1], nV2);
  61398. result.push(nV3);
  61399. result.push(nV2.clone());
  61400. result.push(nV1.clone());
  61401. result.push(nV2.clone());
  61402. result.push(nV3.clone());
  61403. result.push(nV4);
  61404. break;
  61405. }
  61406. if (v3Out) {
  61407. nV1 = vertices[index];
  61408. nV2 = vertices[index + 1];
  61409. nV3 = clipVertices(vertices[index + 2], nV1);
  61410. nV4 = clipVertices(vertices[index + 2], nV2);
  61411. }
  61412. if (nV1 && nV2 && nV3 && nV4) {
  61413. result.push(nV1.clone());
  61414. result.push(nV2.clone());
  61415. result.push(nV3);
  61416. result.push(nV4);
  61417. result.push(nV3.clone());
  61418. result.push(nV2.clone());
  61419. }
  61420. break;
  61421. case 2:
  61422. if (!v1Out) {
  61423. nV1 = vertices[index].clone();
  61424. nV2 = clipVertices(nV1, vertices[index + 1]);
  61425. nV3 = clipVertices(nV1, vertices[index + 2]);
  61426. result.push(nV1);
  61427. result.push(nV2);
  61428. result.push(nV3);
  61429. }
  61430. if (!v2Out) {
  61431. nV1 = vertices[index + 1].clone();
  61432. nV2 = clipVertices(nV1, vertices[index + 2]);
  61433. nV3 = clipVertices(nV1, vertices[index]);
  61434. result.push(nV1);
  61435. result.push(nV2);
  61436. result.push(nV3);
  61437. }
  61438. if (!v3Out) {
  61439. nV1 = vertices[index + 2].clone();
  61440. nV2 = clipVertices(nV1, vertices[index]);
  61441. nV3 = clipVertices(nV1, vertices[index + 1]);
  61442. result.push(nV1);
  61443. result.push(nV2);
  61444. result.push(nV3);
  61445. }
  61446. break;
  61447. case 3:
  61448. break;
  61449. }
  61450. }
  61451. return result;
  61452. };
  61453. for (var index = 0; index < indices.length; index += 3) {
  61454. var faceVertices = new Array();
  61455. faceVertices.push(extractDecalVector3(index));
  61456. faceVertices.push(extractDecalVector3(index + 1));
  61457. faceVertices.push(extractDecalVector3(index + 2));
  61458. // Clip
  61459. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61460. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61461. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61462. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61463. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61464. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61465. if (faceVertices.length === 0) {
  61466. continue;
  61467. }
  61468. // Add UVs and get back to world
  61469. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61470. var vertex = faceVertices[vIndex];
  61471. //TODO check for Int32Array | Uint32Array | Uint16Array
  61472. vertexData.indices.push(currentVertexDataIndex);
  61473. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61474. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61475. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61476. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61477. currentVertexDataIndex++;
  61478. }
  61479. }
  61480. // Return mesh
  61481. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61482. vertexData.applyToMesh(decal);
  61483. decal.position = position.clone();
  61484. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61485. return decal;
  61486. };
  61487. // Privates
  61488. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61489. // extrusion geometry
  61490. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61491. var tangents = path3D.getTangents();
  61492. var normals = path3D.getNormals();
  61493. var binormals = path3D.getBinormals();
  61494. var distances = path3D.getDistances();
  61495. var angle = 0;
  61496. var returnScale = function () { return scale !== null ? scale : 1; };
  61497. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61498. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61499. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61500. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61501. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61502. for (var i = 0; i < curve.length; i++) {
  61503. var shapePath = new Array();
  61504. var angleStep = rotate(i, distances[i]);
  61505. var scaleRatio = scl(i, distances[i]);
  61506. for (var p = 0; p < shape.length; p++) {
  61507. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61508. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61509. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61510. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61511. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61512. shapePath[p] = rotated;
  61513. }
  61514. shapePaths[index] = shapePath;
  61515. angle += angleStep;
  61516. index++;
  61517. }
  61518. // cap
  61519. var capPath = function (shapePath) {
  61520. var pointCap = Array();
  61521. var barycenter = BABYLON.Vector3.Zero();
  61522. var i;
  61523. for (i = 0; i < shapePath.length; i++) {
  61524. barycenter.addInPlace(shapePath[i]);
  61525. }
  61526. barycenter.scaleInPlace(1.0 / shapePath.length);
  61527. for (i = 0; i < shapePath.length; i++) {
  61528. pointCap.push(barycenter);
  61529. }
  61530. return pointCap;
  61531. };
  61532. switch (cap) {
  61533. case BABYLON.Mesh.NO_CAP:
  61534. break;
  61535. case BABYLON.Mesh.CAP_START:
  61536. shapePaths[0] = capPath(shapePaths[2]);
  61537. shapePaths[1] = shapePaths[2];
  61538. break;
  61539. case BABYLON.Mesh.CAP_END:
  61540. shapePaths[index] = shapePaths[index - 1];
  61541. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61542. break;
  61543. case BABYLON.Mesh.CAP_ALL:
  61544. shapePaths[0] = capPath(shapePaths[2]);
  61545. shapePaths[1] = shapePaths[2];
  61546. shapePaths[index] = shapePaths[index - 1];
  61547. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61548. break;
  61549. default:
  61550. break;
  61551. }
  61552. return shapePaths;
  61553. };
  61554. var path3D;
  61555. var pathArray;
  61556. if (instance) { // instance update
  61557. path3D = (instance.path3D).update(curve);
  61558. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61559. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61560. return instance;
  61561. }
  61562. // extruded shape creation
  61563. path3D = new BABYLON.Path3D(curve);
  61564. var newShapePaths = new Array();
  61565. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61566. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61567. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61568. extrudedGeneric.pathArray = pathArray;
  61569. extrudedGeneric.path3D = path3D;
  61570. extrudedGeneric.cap = cap;
  61571. return extrudedGeneric;
  61572. };
  61573. return MeshBuilder;
  61574. }());
  61575. BABYLON.MeshBuilder = MeshBuilder;
  61576. })(BABYLON || (BABYLON = {}));
  61577. //# sourceMappingURL=babylon.meshBuilder.js.map
  61578. var BABYLON;
  61579. (function (BABYLON) {
  61580. /**
  61581. * Draco compression (https://google.github.io/draco/)
  61582. */
  61583. var DracoCompression = /** @class */ (function () {
  61584. /**
  61585. * Constructor
  61586. */
  61587. function DracoCompression() {
  61588. }
  61589. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61590. /**
  61591. * Returns true if the decoder is available.
  61592. */
  61593. get: function () {
  61594. if (typeof DracoDecoderModule !== "undefined") {
  61595. return true;
  61596. }
  61597. var decoder = DracoCompression.Configuration.decoder;
  61598. if (decoder) {
  61599. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61600. return true;
  61601. }
  61602. if (decoder.fallbackUrl) {
  61603. return true;
  61604. }
  61605. }
  61606. return false;
  61607. },
  61608. enumerable: true,
  61609. configurable: true
  61610. });
  61611. /**
  61612. * Stop all async operations and release resources.
  61613. */
  61614. DracoCompression.prototype.dispose = function () {
  61615. };
  61616. /**
  61617. * Decode Draco compressed mesh data to vertex data.
  61618. * @param data The array buffer view for the Draco compression data
  61619. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61620. * @returns A promise that resolves with the decoded vertex data
  61621. */
  61622. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61623. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61624. var module = wrappedModule.module;
  61625. var vertexData = new BABYLON.VertexData();
  61626. var buffer = new module.DecoderBuffer();
  61627. buffer.Init(data, data.byteLength);
  61628. var decoder = new module.Decoder();
  61629. var geometry;
  61630. var status;
  61631. try {
  61632. var type = decoder.GetEncodedGeometryType(buffer);
  61633. switch (type) {
  61634. case module.TRIANGULAR_MESH:
  61635. geometry = new module.Mesh();
  61636. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61637. break;
  61638. case module.POINT_CLOUD:
  61639. geometry = new module.PointCloud();
  61640. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61641. break;
  61642. default:
  61643. throw new Error("Invalid geometry type " + type);
  61644. }
  61645. if (!status.ok() || !geometry.ptr) {
  61646. throw new Error(status.error_msg());
  61647. }
  61648. var numPoints = geometry.num_points();
  61649. if (type === module.TRIANGULAR_MESH) {
  61650. var numFaces = geometry.num_faces();
  61651. var faceIndices = new module.DracoInt32Array();
  61652. try {
  61653. var indices = new Uint32Array(numFaces * 3);
  61654. for (var i = 0; i < numFaces; i++) {
  61655. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61656. var offset = i * 3;
  61657. indices[offset + 0] = faceIndices.GetValue(0);
  61658. indices[offset + 1] = faceIndices.GetValue(1);
  61659. indices[offset + 2] = faceIndices.GetValue(2);
  61660. }
  61661. vertexData.indices = indices;
  61662. }
  61663. finally {
  61664. module.destroy(faceIndices);
  61665. }
  61666. }
  61667. for (var kind in attributes) {
  61668. var uniqueId = attributes[kind];
  61669. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61670. var dracoData = new module.DracoFloat32Array();
  61671. try {
  61672. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61673. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61674. for (var i = 0; i < babylonData.length; i++) {
  61675. babylonData[i] = dracoData.GetValue(i);
  61676. }
  61677. vertexData.set(babylonData, kind);
  61678. }
  61679. finally {
  61680. module.destroy(dracoData);
  61681. }
  61682. }
  61683. }
  61684. finally {
  61685. if (geometry) {
  61686. module.destroy(geometry);
  61687. }
  61688. module.destroy(decoder);
  61689. module.destroy(buffer);
  61690. }
  61691. return vertexData;
  61692. });
  61693. };
  61694. DracoCompression._GetDecoderModule = function () {
  61695. if (!DracoCompression._DecoderModulePromise) {
  61696. var promise = null;
  61697. var config_1 = {};
  61698. if (typeof DracoDecoderModule !== "undefined") {
  61699. promise = Promise.resolve();
  61700. }
  61701. else {
  61702. var decoder = DracoCompression.Configuration.decoder;
  61703. if (decoder) {
  61704. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61705. promise = Promise.all([
  61706. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61707. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61708. config_1.wasmBinary = data;
  61709. })
  61710. ]);
  61711. }
  61712. else if (decoder.fallbackUrl) {
  61713. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61714. }
  61715. }
  61716. }
  61717. if (!promise) {
  61718. throw new Error("Draco decoder module is not available");
  61719. }
  61720. DracoCompression._DecoderModulePromise = promise.then(function () {
  61721. return new Promise(function (resolve) {
  61722. config_1.onModuleLoaded = function (decoderModule) {
  61723. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61724. resolve({ module: decoderModule });
  61725. };
  61726. DracoDecoderModule(config_1);
  61727. });
  61728. });
  61729. }
  61730. return DracoCompression._DecoderModulePromise;
  61731. };
  61732. DracoCompression._LoadScriptAsync = function (url) {
  61733. return new Promise(function (resolve, reject) {
  61734. BABYLON.Tools.LoadScript(url, function () {
  61735. resolve();
  61736. }, function (message) {
  61737. reject(new Error(message));
  61738. });
  61739. });
  61740. };
  61741. DracoCompression._LoadFileAsync = function (url) {
  61742. return new Promise(function (resolve, reject) {
  61743. BABYLON.Tools.LoadFile(url, function (data) {
  61744. resolve(data);
  61745. }, undefined, undefined, true, function (request, exception) {
  61746. reject(exception);
  61747. });
  61748. });
  61749. };
  61750. /**
  61751. * The configuration.
  61752. */
  61753. DracoCompression.Configuration = {
  61754. decoder: {
  61755. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61756. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61757. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61758. }
  61759. };
  61760. return DracoCompression;
  61761. }());
  61762. BABYLON.DracoCompression = DracoCompression;
  61763. })(BABYLON || (BABYLON = {}));
  61764. //# sourceMappingURL=babylon.dracoCompression.js.map
  61765. var BABYLON;
  61766. (function (BABYLON) {
  61767. var AudioEngine = /** @class */ (function () {
  61768. function AudioEngine() {
  61769. this._audioContext = null;
  61770. this._audioContextInitialized = false;
  61771. this.canUseWebAudio = false;
  61772. this.WarnedWebAudioUnsupported = false;
  61773. this.unlocked = false;
  61774. this.isMP3supported = false;
  61775. this.isOGGsupported = false;
  61776. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61777. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61778. this.canUseWebAudio = true;
  61779. }
  61780. var audioElem = document.createElement('audio');
  61781. try {
  61782. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61783. this.isMP3supported = true;
  61784. }
  61785. }
  61786. catch (e) {
  61787. // protect error during capability check.
  61788. }
  61789. try {
  61790. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61791. this.isOGGsupported = true;
  61792. }
  61793. }
  61794. catch (e) {
  61795. // protect error during capability check.
  61796. }
  61797. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61798. this._unlockiOSaudio();
  61799. }
  61800. else {
  61801. this.unlocked = true;
  61802. }
  61803. }
  61804. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61805. get: function () {
  61806. if (!this._audioContextInitialized) {
  61807. this._initializeAudioContext();
  61808. }
  61809. return this._audioContext;
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. AudioEngine.prototype._unlockiOSaudio = function () {
  61815. var _this = this;
  61816. var unlockaudio = function () {
  61817. if (!_this.audioContext) {
  61818. return;
  61819. }
  61820. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61821. var source = _this.audioContext.createBufferSource();
  61822. source.buffer = buffer;
  61823. source.connect(_this.audioContext.destination);
  61824. source.start(0);
  61825. setTimeout(function () {
  61826. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61827. _this.unlocked = true;
  61828. window.removeEventListener('touchend', unlockaudio, false);
  61829. if (_this.onAudioUnlocked) {
  61830. _this.onAudioUnlocked();
  61831. }
  61832. }
  61833. }, 0);
  61834. };
  61835. window.addEventListener('touchend', unlockaudio, false);
  61836. };
  61837. AudioEngine.prototype._initializeAudioContext = function () {
  61838. try {
  61839. if (this.canUseWebAudio) {
  61840. this._audioContext = new AudioContext();
  61841. // create a global volume gain node
  61842. this.masterGain = this._audioContext.createGain();
  61843. this.masterGain.gain.value = 1;
  61844. this.masterGain.connect(this._audioContext.destination);
  61845. this._audioContextInitialized = true;
  61846. }
  61847. }
  61848. catch (e) {
  61849. this.canUseWebAudio = false;
  61850. BABYLON.Tools.Error("Web Audio: " + e.message);
  61851. }
  61852. };
  61853. AudioEngine.prototype.dispose = function () {
  61854. if (this.canUseWebAudio && this._audioContextInitialized) {
  61855. if (this._connectedAnalyser && this._audioContext) {
  61856. this._connectedAnalyser.stopDebugCanvas();
  61857. this._connectedAnalyser.dispose();
  61858. this.masterGain.disconnect();
  61859. this.masterGain.connect(this._audioContext.destination);
  61860. this._connectedAnalyser = null;
  61861. }
  61862. this.masterGain.gain.value = 1;
  61863. }
  61864. this.WarnedWebAudioUnsupported = false;
  61865. };
  61866. AudioEngine.prototype.getGlobalVolume = function () {
  61867. if (this.canUseWebAudio && this._audioContextInitialized) {
  61868. return this.masterGain.gain.value;
  61869. }
  61870. else {
  61871. return -1;
  61872. }
  61873. };
  61874. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61875. if (this.canUseWebAudio && this._audioContextInitialized) {
  61876. this.masterGain.gain.value = newVolume;
  61877. }
  61878. };
  61879. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61880. if (this._connectedAnalyser) {
  61881. this._connectedAnalyser.stopDebugCanvas();
  61882. }
  61883. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61884. this._connectedAnalyser = analyser;
  61885. this.masterGain.disconnect();
  61886. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61887. }
  61888. };
  61889. return AudioEngine;
  61890. }());
  61891. BABYLON.AudioEngine = AudioEngine;
  61892. })(BABYLON || (BABYLON = {}));
  61893. //# sourceMappingURL=babylon.audioEngine.js.map
  61894. var BABYLON;
  61895. (function (BABYLON) {
  61896. var Sound = /** @class */ (function () {
  61897. /**
  61898. * Create a sound and attach it to a scene
  61899. * @param name Name of your sound
  61900. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61901. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61902. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61903. */
  61904. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61905. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61906. var _this = this;
  61907. this.autoplay = false;
  61908. this.loop = false;
  61909. this.useCustomAttenuation = false;
  61910. this.spatialSound = false;
  61911. this.refDistance = 1;
  61912. this.rolloffFactor = 1;
  61913. this.maxDistance = 100;
  61914. this.distanceModel = "linear";
  61915. this._panningModel = "equalpower";
  61916. this._playbackRate = 1;
  61917. this._streaming = false;
  61918. this._startTime = 0;
  61919. this._startOffset = 0;
  61920. this._position = BABYLON.Vector3.Zero();
  61921. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61922. this._volume = 1;
  61923. this._isReadyToPlay = false;
  61924. this.isPlaying = false;
  61925. this.isPaused = false;
  61926. this._isDirectional = false;
  61927. // Used if you'd like to create a directional sound.
  61928. // If not set, the sound will be omnidirectional
  61929. this._coneInnerAngle = 360;
  61930. this._coneOuterAngle = 360;
  61931. this._coneOuterGain = 0;
  61932. this._isOutputConnected = false;
  61933. this._urlType = "Unknown";
  61934. this.name = name;
  61935. this._scene = scene;
  61936. this._readyToPlayCallback = readyToPlayCallback;
  61937. // Default custom attenuation function is a linear attenuation
  61938. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61939. if (currentDistance < maxDistance) {
  61940. return currentVolume * (1 - currentDistance / maxDistance);
  61941. }
  61942. else {
  61943. return 0;
  61944. }
  61945. };
  61946. if (options) {
  61947. this.autoplay = options.autoplay || false;
  61948. this.loop = options.loop || false;
  61949. // if volume === 0, we need another way to check this option
  61950. if (options.volume !== undefined) {
  61951. this._volume = options.volume;
  61952. }
  61953. this.spatialSound = options.spatialSound || false;
  61954. this.maxDistance = options.maxDistance || 100;
  61955. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61956. this.rolloffFactor = options.rolloffFactor || 1;
  61957. this.refDistance = options.refDistance || 1;
  61958. this.distanceModel = options.distanceModel || "linear";
  61959. this._playbackRate = options.playbackRate || 1;
  61960. this._streaming = options.streaming || false;
  61961. }
  61962. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61963. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61964. this._soundGain.gain.value = this._volume;
  61965. this._inputAudioNode = this._soundGain;
  61966. this._ouputAudioNode = this._soundGain;
  61967. if (this.spatialSound) {
  61968. this._createSpatialParameters();
  61969. }
  61970. this._scene.mainSoundTrack.AddSound(this);
  61971. var validParameter = true;
  61972. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61973. if (urlOrArrayBuffer) {
  61974. try {
  61975. if (typeof (urlOrArrayBuffer) === "string")
  61976. this._urlType = "String";
  61977. if (Array.isArray(urlOrArrayBuffer))
  61978. this._urlType = "Array";
  61979. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61980. this._urlType = "ArrayBuffer";
  61981. var urls = [];
  61982. var codecSupportedFound = false;
  61983. switch (this._urlType) {
  61984. case "ArrayBuffer":
  61985. if (urlOrArrayBuffer.byteLength > 0) {
  61986. codecSupportedFound = true;
  61987. this._soundLoaded(urlOrArrayBuffer);
  61988. }
  61989. break;
  61990. case "String":
  61991. urls.push(urlOrArrayBuffer);
  61992. case "Array":
  61993. if (urls.length === 0)
  61994. urls = urlOrArrayBuffer;
  61995. // If we found a supported format, we load it immediately and stop the loop
  61996. for (var i = 0; i < urls.length; i++) {
  61997. var url = urls[i];
  61998. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61999. codecSupportedFound = true;
  62000. }
  62001. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62002. codecSupportedFound = true;
  62003. }
  62004. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62005. codecSupportedFound = true;
  62006. }
  62007. if (url.indexOf("blob:") !== -1) {
  62008. codecSupportedFound = true;
  62009. }
  62010. if (codecSupportedFound) {
  62011. // Loading sound using XHR2
  62012. if (!this._streaming) {
  62013. this._scene._loadFile(url, function (data) {
  62014. _this._soundLoaded(data);
  62015. }, undefined, true, true, function (exception) {
  62016. if (exception) {
  62017. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62018. }
  62019. BABYLON.Tools.Error("Sound creation aborted.");
  62020. _this._scene.mainSoundTrack.RemoveSound(_this);
  62021. });
  62022. }
  62023. // Streaming sound using HTML5 Audio tag
  62024. else {
  62025. this._htmlAudioElement = new Audio(url);
  62026. this._htmlAudioElement.controls = false;
  62027. this._htmlAudioElement.loop = this.loop;
  62028. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62029. this._htmlAudioElement.preload = "auto";
  62030. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62031. _this._isReadyToPlay = true;
  62032. if (_this.autoplay) {
  62033. _this.play();
  62034. }
  62035. if (_this._readyToPlayCallback) {
  62036. _this._readyToPlayCallback();
  62037. }
  62038. });
  62039. document.body.appendChild(this._htmlAudioElement);
  62040. }
  62041. break;
  62042. }
  62043. }
  62044. break;
  62045. default:
  62046. validParameter = false;
  62047. break;
  62048. }
  62049. if (!validParameter) {
  62050. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62051. }
  62052. else {
  62053. if (!codecSupportedFound) {
  62054. this._isReadyToPlay = true;
  62055. // Simulating a ready to play event to avoid breaking code path
  62056. if (this._readyToPlayCallback) {
  62057. window.setTimeout(function () {
  62058. if (_this._readyToPlayCallback) {
  62059. _this._readyToPlayCallback();
  62060. }
  62061. }, 1000);
  62062. }
  62063. }
  62064. }
  62065. }
  62066. catch (ex) {
  62067. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62068. this._scene.mainSoundTrack.RemoveSound(this);
  62069. }
  62070. }
  62071. }
  62072. else {
  62073. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62074. this._scene.mainSoundTrack.AddSound(this);
  62075. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62076. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62077. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62078. }
  62079. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62080. if (this._readyToPlayCallback) {
  62081. window.setTimeout(function () {
  62082. if (_this._readyToPlayCallback) {
  62083. _this._readyToPlayCallback();
  62084. }
  62085. }, 1000);
  62086. }
  62087. }
  62088. }
  62089. Sound.prototype.dispose = function () {
  62090. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62091. if (this.isPlaying) {
  62092. this.stop();
  62093. }
  62094. this._isReadyToPlay = false;
  62095. if (this.soundTrackId === -1) {
  62096. this._scene.mainSoundTrack.RemoveSound(this);
  62097. }
  62098. else {
  62099. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62100. }
  62101. if (this._soundGain) {
  62102. this._soundGain.disconnect();
  62103. this._soundGain = null;
  62104. }
  62105. if (this._soundPanner) {
  62106. this._soundPanner.disconnect();
  62107. this._soundPanner = null;
  62108. }
  62109. if (this._soundSource) {
  62110. this._soundSource.disconnect();
  62111. this._soundSource = null;
  62112. }
  62113. this._audioBuffer = null;
  62114. if (this._htmlAudioElement) {
  62115. this._htmlAudioElement.pause();
  62116. this._htmlAudioElement.src = "";
  62117. document.body.removeChild(this._htmlAudioElement);
  62118. }
  62119. if (this._connectedMesh && this._registerFunc) {
  62120. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62121. this._connectedMesh = null;
  62122. }
  62123. }
  62124. };
  62125. Sound.prototype.isReady = function () {
  62126. return this._isReadyToPlay;
  62127. };
  62128. Sound.prototype._soundLoaded = function (audioData) {
  62129. var _this = this;
  62130. if (!BABYLON.Engine.audioEngine.audioContext) {
  62131. return;
  62132. }
  62133. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62134. _this._audioBuffer = buffer;
  62135. _this._isReadyToPlay = true;
  62136. if (_this.autoplay) {
  62137. _this.play();
  62138. }
  62139. if (_this._readyToPlayCallback) {
  62140. _this._readyToPlayCallback();
  62141. }
  62142. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62143. };
  62144. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62146. this._audioBuffer = audioBuffer;
  62147. this._isReadyToPlay = true;
  62148. }
  62149. };
  62150. Sound.prototype.updateOptions = function (options) {
  62151. if (options) {
  62152. this.loop = options.loop || this.loop;
  62153. this.maxDistance = options.maxDistance || this.maxDistance;
  62154. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62155. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62156. this.refDistance = options.refDistance || this.refDistance;
  62157. this.distanceModel = options.distanceModel || this.distanceModel;
  62158. this._playbackRate = options.playbackRate || this._playbackRate;
  62159. this._updateSpatialParameters();
  62160. if (this.isPlaying) {
  62161. if (this._streaming) {
  62162. this._htmlAudioElement.playbackRate = this._playbackRate;
  62163. }
  62164. else {
  62165. if (this._soundSource) {
  62166. this._soundSource.playbackRate.value = this._playbackRate;
  62167. }
  62168. }
  62169. }
  62170. }
  62171. };
  62172. Sound.prototype._createSpatialParameters = function () {
  62173. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62174. if (this._scene.headphone) {
  62175. this._panningModel = "HRTF";
  62176. }
  62177. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62178. this._updateSpatialParameters();
  62179. this._soundPanner.connect(this._ouputAudioNode);
  62180. this._inputAudioNode = this._soundPanner;
  62181. }
  62182. };
  62183. Sound.prototype._updateSpatialParameters = function () {
  62184. if (this.spatialSound && this._soundPanner) {
  62185. if (this.useCustomAttenuation) {
  62186. // Tricks to disable in a way embedded Web Audio attenuation
  62187. this._soundPanner.distanceModel = "linear";
  62188. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62189. this._soundPanner.refDistance = 1;
  62190. this._soundPanner.rolloffFactor = 1;
  62191. this._soundPanner.panningModel = this._panningModel;
  62192. }
  62193. else {
  62194. this._soundPanner.distanceModel = this.distanceModel;
  62195. this._soundPanner.maxDistance = this.maxDistance;
  62196. this._soundPanner.refDistance = this.refDistance;
  62197. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62198. this._soundPanner.panningModel = this._panningModel;
  62199. }
  62200. }
  62201. };
  62202. Sound.prototype.switchPanningModelToHRTF = function () {
  62203. this._panningModel = "HRTF";
  62204. this._switchPanningModel();
  62205. };
  62206. Sound.prototype.switchPanningModelToEqualPower = function () {
  62207. this._panningModel = "equalpower";
  62208. this._switchPanningModel();
  62209. };
  62210. Sound.prototype._switchPanningModel = function () {
  62211. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62212. this._soundPanner.panningModel = this._panningModel;
  62213. }
  62214. };
  62215. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62216. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62217. if (this._isOutputConnected) {
  62218. this._ouputAudioNode.disconnect();
  62219. }
  62220. this._ouputAudioNode.connect(soundTrackAudioNode);
  62221. this._isOutputConnected = true;
  62222. }
  62223. };
  62224. /**
  62225. * Transform this sound into a directional source
  62226. * @param coneInnerAngle Size of the inner cone in degree
  62227. * @param coneOuterAngle Size of the outer cone in degree
  62228. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62229. */
  62230. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62231. if (coneOuterAngle < coneInnerAngle) {
  62232. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62233. return;
  62234. }
  62235. this._coneInnerAngle = coneInnerAngle;
  62236. this._coneOuterAngle = coneOuterAngle;
  62237. this._coneOuterGain = coneOuterGain;
  62238. this._isDirectional = true;
  62239. if (this.isPlaying && this.loop) {
  62240. this.stop();
  62241. this.play();
  62242. }
  62243. };
  62244. Sound.prototype.setPosition = function (newPosition) {
  62245. this._position = newPosition;
  62246. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62247. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62248. }
  62249. };
  62250. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62251. this._localDirection = newLocalDirection;
  62252. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62253. this._updateDirection();
  62254. }
  62255. };
  62256. Sound.prototype._updateDirection = function () {
  62257. if (!this._connectedMesh || !this._soundPanner) {
  62258. return;
  62259. }
  62260. var mat = this._connectedMesh.getWorldMatrix();
  62261. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62262. direction.normalize();
  62263. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62264. };
  62265. Sound.prototype.updateDistanceFromListener = function () {
  62266. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62267. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62268. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62269. }
  62270. };
  62271. Sound.prototype.setAttenuationFunction = function (callback) {
  62272. this._customAttenuationFunction = callback;
  62273. };
  62274. /**
  62275. * Play the sound
  62276. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62277. * @param offset (optional) Start the sound setting it at a specific time
  62278. */
  62279. Sound.prototype.play = function (time, offset) {
  62280. var _this = this;
  62281. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62282. try {
  62283. if (this._startOffset < 0) {
  62284. time = -this._startOffset;
  62285. this._startOffset = 0;
  62286. }
  62287. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62288. if (!this._soundSource || !this._streamingSource) {
  62289. if (this.spatialSound && this._soundPanner) {
  62290. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62291. if (this._isDirectional) {
  62292. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62293. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62294. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62295. if (this._connectedMesh) {
  62296. this._updateDirection();
  62297. }
  62298. else {
  62299. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62300. }
  62301. }
  62302. }
  62303. }
  62304. if (this._streaming) {
  62305. if (!this._streamingSource) {
  62306. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62307. this._htmlAudioElement.onended = function () { _this._onended(); };
  62308. this._htmlAudioElement.playbackRate = this._playbackRate;
  62309. }
  62310. this._streamingSource.disconnect();
  62311. this._streamingSource.connect(this._inputAudioNode);
  62312. this._htmlAudioElement.play();
  62313. }
  62314. else {
  62315. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62316. this._soundSource.buffer = this._audioBuffer;
  62317. this._soundSource.connect(this._inputAudioNode);
  62318. this._soundSource.loop = this.loop;
  62319. this._soundSource.playbackRate.value = this._playbackRate;
  62320. this._soundSource.onended = function () { _this._onended(); };
  62321. if (this._soundSource.buffer) {
  62322. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62323. }
  62324. }
  62325. this._startTime = startTime;
  62326. this.isPlaying = true;
  62327. this.isPaused = false;
  62328. }
  62329. catch (ex) {
  62330. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62331. }
  62332. }
  62333. };
  62334. Sound.prototype._onended = function () {
  62335. this.isPlaying = false;
  62336. if (this.onended) {
  62337. this.onended();
  62338. }
  62339. };
  62340. /**
  62341. * Stop the sound
  62342. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62343. */
  62344. Sound.prototype.stop = function (time) {
  62345. if (this.isPlaying) {
  62346. if (this._streaming) {
  62347. this._htmlAudioElement.pause();
  62348. // Test needed for Firefox or it will generate an Invalid State Error
  62349. if (this._htmlAudioElement.currentTime > 0) {
  62350. this._htmlAudioElement.currentTime = 0;
  62351. }
  62352. }
  62353. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62354. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62355. this._soundSource.stop(stopTime);
  62356. this._soundSource.onended = function () { };
  62357. if (!this.isPaused) {
  62358. this._startOffset = 0;
  62359. }
  62360. }
  62361. this.isPlaying = false;
  62362. }
  62363. };
  62364. Sound.prototype.pause = function () {
  62365. if (this.isPlaying) {
  62366. this.isPaused = true;
  62367. if (this._streaming) {
  62368. this._htmlAudioElement.pause();
  62369. }
  62370. else if (BABYLON.Engine.audioEngine.audioContext) {
  62371. this.stop(0);
  62372. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62373. }
  62374. }
  62375. };
  62376. Sound.prototype.setVolume = function (newVolume, time) {
  62377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62378. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62379. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62380. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62381. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62382. }
  62383. else {
  62384. this._soundGain.gain.value = newVolume;
  62385. }
  62386. }
  62387. this._volume = newVolume;
  62388. };
  62389. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62390. this._playbackRate = newPlaybackRate;
  62391. if (this.isPlaying) {
  62392. if (this._streaming) {
  62393. this._htmlAudioElement.playbackRate = this._playbackRate;
  62394. }
  62395. else if (this._soundSource) {
  62396. this._soundSource.playbackRate.value = this._playbackRate;
  62397. }
  62398. }
  62399. };
  62400. Sound.prototype.getVolume = function () {
  62401. return this._volume;
  62402. };
  62403. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62404. var _this = this;
  62405. if (this._connectedMesh && this._registerFunc) {
  62406. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62407. this._registerFunc = null;
  62408. }
  62409. this._connectedMesh = meshToConnectTo;
  62410. if (!this.spatialSound) {
  62411. this.spatialSound = true;
  62412. this._createSpatialParameters();
  62413. if (this.isPlaying && this.loop) {
  62414. this.stop();
  62415. this.play();
  62416. }
  62417. }
  62418. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62419. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62420. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62421. };
  62422. Sound.prototype.detachFromMesh = function () {
  62423. if (this._connectedMesh && this._registerFunc) {
  62424. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62425. this._registerFunc = null;
  62426. this._connectedMesh = null;
  62427. }
  62428. };
  62429. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62430. if (!node.getBoundingInfo) {
  62431. return;
  62432. }
  62433. var mesh = node;
  62434. var boundingInfo = mesh.getBoundingInfo();
  62435. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62436. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62437. this._updateDirection();
  62438. }
  62439. };
  62440. Sound.prototype.clone = function () {
  62441. var _this = this;
  62442. if (!this._streaming) {
  62443. var setBufferAndRun = function () {
  62444. if (_this._isReadyToPlay) {
  62445. clonedSound._audioBuffer = _this.getAudioBuffer();
  62446. clonedSound._isReadyToPlay = true;
  62447. if (clonedSound.autoplay) {
  62448. clonedSound.play();
  62449. }
  62450. }
  62451. else {
  62452. window.setTimeout(setBufferAndRun, 300);
  62453. }
  62454. };
  62455. var currentOptions = {
  62456. autoplay: this.autoplay, loop: this.loop,
  62457. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62458. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62459. refDistance: this.refDistance, distanceModel: this.distanceModel
  62460. };
  62461. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62462. if (this.useCustomAttenuation) {
  62463. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62464. }
  62465. clonedSound.setPosition(this._position);
  62466. clonedSound.setPlaybackRate(this._playbackRate);
  62467. setBufferAndRun();
  62468. return clonedSound;
  62469. }
  62470. // Can't clone a streaming sound
  62471. else {
  62472. return null;
  62473. }
  62474. };
  62475. Sound.prototype.getAudioBuffer = function () {
  62476. return this._audioBuffer;
  62477. };
  62478. Sound.prototype.serialize = function () {
  62479. var serializationObject = {
  62480. name: this.name,
  62481. url: this.name,
  62482. autoplay: this.autoplay,
  62483. loop: this.loop,
  62484. volume: this._volume,
  62485. spatialSound: this.spatialSound,
  62486. maxDistance: this.maxDistance,
  62487. rolloffFactor: this.rolloffFactor,
  62488. refDistance: this.refDistance,
  62489. distanceModel: this.distanceModel,
  62490. playbackRate: this._playbackRate,
  62491. panningModel: this._panningModel,
  62492. soundTrackId: this.soundTrackId
  62493. };
  62494. if (this.spatialSound) {
  62495. if (this._connectedMesh)
  62496. serializationObject.connectedMeshId = this._connectedMesh.id;
  62497. serializationObject.position = this._position.asArray();
  62498. serializationObject.refDistance = this.refDistance;
  62499. serializationObject.distanceModel = this.distanceModel;
  62500. serializationObject.isDirectional = this._isDirectional;
  62501. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62502. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62503. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62504. serializationObject.coneOuterGain = this._coneOuterGain;
  62505. }
  62506. return serializationObject;
  62507. };
  62508. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62509. var soundName = parsedSound.name;
  62510. var soundUrl;
  62511. if (parsedSound.url) {
  62512. soundUrl = rootUrl + parsedSound.url;
  62513. }
  62514. else {
  62515. soundUrl = rootUrl + soundName;
  62516. }
  62517. var options = {
  62518. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62519. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62520. rolloffFactor: parsedSound.rolloffFactor,
  62521. refDistance: parsedSound.refDistance,
  62522. distanceModel: parsedSound.distanceModel,
  62523. playbackRate: parsedSound.playbackRate
  62524. };
  62525. var newSound;
  62526. if (!sourceSound) {
  62527. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62528. scene._addPendingData(newSound);
  62529. }
  62530. else {
  62531. var setBufferAndRun = function () {
  62532. if (sourceSound._isReadyToPlay) {
  62533. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62534. newSound._isReadyToPlay = true;
  62535. if (newSound.autoplay) {
  62536. newSound.play();
  62537. }
  62538. }
  62539. else {
  62540. window.setTimeout(setBufferAndRun, 300);
  62541. }
  62542. };
  62543. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62544. setBufferAndRun();
  62545. }
  62546. if (parsedSound.position) {
  62547. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62548. newSound.setPosition(soundPosition);
  62549. }
  62550. if (parsedSound.isDirectional) {
  62551. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62552. if (parsedSound.localDirectionToMesh) {
  62553. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62554. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62555. }
  62556. }
  62557. if (parsedSound.connectedMeshId) {
  62558. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62559. if (connectedMesh) {
  62560. newSound.attachToMesh(connectedMesh);
  62561. }
  62562. }
  62563. return newSound;
  62564. };
  62565. return Sound;
  62566. }());
  62567. BABYLON.Sound = Sound;
  62568. })(BABYLON || (BABYLON = {}));
  62569. //# sourceMappingURL=babylon.sound.js.map
  62570. var BABYLON;
  62571. (function (BABYLON) {
  62572. var SoundTrack = /** @class */ (function () {
  62573. function SoundTrack(scene, options) {
  62574. this.id = -1;
  62575. this._isMainTrack = false;
  62576. this._isInitialized = false;
  62577. this._scene = scene;
  62578. this.soundCollection = new Array();
  62579. this._options = options;
  62580. if (!this._isMainTrack) {
  62581. this._scene.soundTracks.push(this);
  62582. this.id = this._scene.soundTracks.length - 1;
  62583. }
  62584. }
  62585. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62586. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62587. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62588. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62589. if (this._options) {
  62590. if (this._options.volume) {
  62591. this._outputAudioNode.gain.value = this._options.volume;
  62592. }
  62593. if (this._options.mainTrack) {
  62594. this._isMainTrack = this._options.mainTrack;
  62595. }
  62596. }
  62597. this._isInitialized = true;
  62598. }
  62599. };
  62600. SoundTrack.prototype.dispose = function () {
  62601. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62602. if (this._connectedAnalyser) {
  62603. this._connectedAnalyser.stopDebugCanvas();
  62604. }
  62605. while (this.soundCollection.length) {
  62606. this.soundCollection[0].dispose();
  62607. }
  62608. if (this._outputAudioNode) {
  62609. this._outputAudioNode.disconnect();
  62610. }
  62611. this._outputAudioNode = null;
  62612. }
  62613. };
  62614. SoundTrack.prototype.AddSound = function (sound) {
  62615. if (!this._isInitialized) {
  62616. this._initializeSoundTrackAudioGraph();
  62617. }
  62618. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62619. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62620. }
  62621. if (sound.soundTrackId) {
  62622. if (sound.soundTrackId === -1) {
  62623. this._scene.mainSoundTrack.RemoveSound(sound);
  62624. }
  62625. else {
  62626. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62627. }
  62628. }
  62629. this.soundCollection.push(sound);
  62630. sound.soundTrackId = this.id;
  62631. };
  62632. SoundTrack.prototype.RemoveSound = function (sound) {
  62633. var index = this.soundCollection.indexOf(sound);
  62634. if (index !== -1) {
  62635. this.soundCollection.splice(index, 1);
  62636. }
  62637. };
  62638. SoundTrack.prototype.setVolume = function (newVolume) {
  62639. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62640. this._outputAudioNode.gain.value = newVolume;
  62641. }
  62642. };
  62643. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62645. for (var i = 0; i < this.soundCollection.length; i++) {
  62646. this.soundCollection[i].switchPanningModelToHRTF();
  62647. }
  62648. }
  62649. };
  62650. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62651. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62652. for (var i = 0; i < this.soundCollection.length; i++) {
  62653. this.soundCollection[i].switchPanningModelToEqualPower();
  62654. }
  62655. }
  62656. };
  62657. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62658. if (this._connectedAnalyser) {
  62659. this._connectedAnalyser.stopDebugCanvas();
  62660. }
  62661. this._connectedAnalyser = analyser;
  62662. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62663. this._outputAudioNode.disconnect();
  62664. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62665. }
  62666. };
  62667. return SoundTrack;
  62668. }());
  62669. BABYLON.SoundTrack = SoundTrack;
  62670. })(BABYLON || (BABYLON = {}));
  62671. //# sourceMappingURL=babylon.soundtrack.js.map
  62672. var BABYLON;
  62673. (function (BABYLON) {
  62674. /**
  62675. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62676. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62677. */
  62678. var Analyser = /** @class */ (function () {
  62679. /**
  62680. * Creates a new analyser
  62681. * @param scene defines hosting scene
  62682. */
  62683. function Analyser(scene) {
  62684. /**
  62685. * Gets or sets the smoothing
  62686. * @ignorenaming
  62687. */
  62688. this.SMOOTHING = 0.75;
  62689. /**
  62690. * Gets or sets the FFT table size
  62691. * @ignorenaming
  62692. */
  62693. this.FFT_SIZE = 512;
  62694. /**
  62695. * Gets or sets the bar graph amplitude
  62696. * @ignorenaming
  62697. */
  62698. this.BARGRAPHAMPLITUDE = 256;
  62699. /**
  62700. * Gets or sets the position of the debug canvas
  62701. * @ignorenaming
  62702. */
  62703. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62704. /**
  62705. * Gets or sets the debug canvas size
  62706. * @ignorenaming
  62707. */
  62708. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62709. this._scene = scene;
  62710. this._audioEngine = BABYLON.Engine.audioEngine;
  62711. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62712. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62713. this._webAudioAnalyser.minDecibels = -140;
  62714. this._webAudioAnalyser.maxDecibels = 0;
  62715. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62716. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62717. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62718. }
  62719. }
  62720. /**
  62721. * Get the number of data values you will have to play with for the visualization
  62722. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62723. * @returns a number
  62724. */
  62725. Analyser.prototype.getFrequencyBinCount = function () {
  62726. if (this._audioEngine.canUseWebAudio) {
  62727. return this._webAudioAnalyser.frequencyBinCount;
  62728. }
  62729. else {
  62730. return 0;
  62731. }
  62732. };
  62733. /**
  62734. * Gets the current frequency data as a byte array
  62735. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62736. * @returns a Uint8Array
  62737. */
  62738. Analyser.prototype.getByteFrequencyData = function () {
  62739. if (this._audioEngine.canUseWebAudio) {
  62740. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62741. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62742. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62743. }
  62744. return this._byteFreqs;
  62745. };
  62746. /**
  62747. * Gets the current waveform as a byte array
  62748. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62749. * @returns a Uint8Array
  62750. */
  62751. Analyser.prototype.getByteTimeDomainData = function () {
  62752. if (this._audioEngine.canUseWebAudio) {
  62753. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62754. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62755. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62756. }
  62757. return this._byteTime;
  62758. };
  62759. /**
  62760. * Gets the current frequency data as a float array
  62761. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62762. * @returns a Float32Array
  62763. */
  62764. Analyser.prototype.getFloatFrequencyData = function () {
  62765. if (this._audioEngine.canUseWebAudio) {
  62766. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62767. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62768. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62769. }
  62770. return this._floatFreqs;
  62771. };
  62772. /**
  62773. * Renders the debug canvas
  62774. */
  62775. Analyser.prototype.drawDebugCanvas = function () {
  62776. var _this = this;
  62777. if (this._audioEngine.canUseWebAudio) {
  62778. if (!this._debugCanvas) {
  62779. this._debugCanvas = document.createElement("canvas");
  62780. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62781. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62782. this._debugCanvas.style.position = "absolute";
  62783. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62784. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62785. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62786. document.body.appendChild(this._debugCanvas);
  62787. this._registerFunc = function () {
  62788. _this.drawDebugCanvas();
  62789. };
  62790. this._scene.registerBeforeRender(this._registerFunc);
  62791. }
  62792. if (this._registerFunc && this._debugCanvasContext) {
  62793. var workingArray = this.getByteFrequencyData();
  62794. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62795. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62796. // Draw the frequency domain chart.
  62797. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62798. var value = workingArray[i];
  62799. var percent = value / this.BARGRAPHAMPLITUDE;
  62800. var height = this.DEBUGCANVASSIZE.height * percent;
  62801. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62802. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62803. var hue = i / this.getFrequencyBinCount() * 360;
  62804. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62805. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62806. }
  62807. }
  62808. }
  62809. };
  62810. /**
  62811. * Stops rendering the debug canvas and removes it
  62812. */
  62813. Analyser.prototype.stopDebugCanvas = function () {
  62814. if (this._debugCanvas) {
  62815. if (this._registerFunc) {
  62816. this._scene.unregisterBeforeRender(this._registerFunc);
  62817. this._registerFunc = null;
  62818. }
  62819. document.body.removeChild(this._debugCanvas);
  62820. this._debugCanvas = null;
  62821. this._debugCanvasContext = null;
  62822. }
  62823. };
  62824. /**
  62825. * Connects two audio nodes
  62826. * @param inputAudioNode defines first node to connect
  62827. * @param outputAudioNode defines second node to connect
  62828. */
  62829. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62830. if (this._audioEngine.canUseWebAudio) {
  62831. inputAudioNode.connect(this._webAudioAnalyser);
  62832. this._webAudioAnalyser.connect(outputAudioNode);
  62833. }
  62834. };
  62835. /**
  62836. * Releases all associated resources
  62837. */
  62838. Analyser.prototype.dispose = function () {
  62839. if (this._audioEngine.canUseWebAudio) {
  62840. this._webAudioAnalyser.disconnect();
  62841. }
  62842. };
  62843. return Analyser;
  62844. }());
  62845. BABYLON.Analyser = Analyser;
  62846. })(BABYLON || (BABYLON = {}));
  62847. //# sourceMappingURL=babylon.analyser.js.map
  62848. var BABYLON;
  62849. (function (BABYLON) {
  62850. var CubeTexture = /** @class */ (function (_super) {
  62851. __extends(CubeTexture, _super);
  62852. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62853. if (extensions === void 0) { extensions = null; }
  62854. if (noMipmap === void 0) { noMipmap = false; }
  62855. if (files === void 0) { files = null; }
  62856. if (onLoad === void 0) { onLoad = null; }
  62857. if (onError === void 0) { onError = null; }
  62858. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62859. if (prefiltered === void 0) { prefiltered = false; }
  62860. if (forcedExtension === void 0) { forcedExtension = null; }
  62861. var _this = _super.call(this, scene) || this;
  62862. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62863. /**
  62864. * Gets or sets the center of the bounding box associated with the cube texture
  62865. * It must define where the camera used to render the texture was set
  62866. */
  62867. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62868. _this._rotationY = 0;
  62869. _this.name = rootUrl;
  62870. _this.url = rootUrl;
  62871. _this._noMipmap = noMipmap;
  62872. _this.hasAlpha = false;
  62873. _this._format = format;
  62874. _this._prefiltered = prefiltered;
  62875. _this.isCube = true;
  62876. _this._textureMatrix = BABYLON.Matrix.Identity();
  62877. if (prefiltered) {
  62878. _this.gammaSpace = false;
  62879. }
  62880. if (!rootUrl && !files) {
  62881. return _this;
  62882. }
  62883. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62884. var lastDot = rootUrl.lastIndexOf(".");
  62885. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62886. var isDDS = (extension === ".dds");
  62887. if (!files) {
  62888. if (!isDDS && !extensions) {
  62889. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62890. }
  62891. files = [];
  62892. if (extensions) {
  62893. for (var index = 0; index < extensions.length; index++) {
  62894. files.push(rootUrl + extensions[index]);
  62895. }
  62896. }
  62897. }
  62898. _this._files = files;
  62899. if (!_this._texture) {
  62900. if (!scene.useDelayedTextureLoading) {
  62901. if (prefiltered) {
  62902. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62903. }
  62904. else {
  62905. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62906. }
  62907. }
  62908. else {
  62909. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62910. }
  62911. }
  62912. else if (onLoad) {
  62913. if (_this._texture.isReady) {
  62914. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62915. }
  62916. else {
  62917. _this._texture.onLoadedObservable.add(onLoad);
  62918. }
  62919. }
  62920. return _this;
  62921. }
  62922. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62923. get: function () {
  62924. return this._boundingBoxSize;
  62925. },
  62926. /**
  62927. * Gets or sets the size of the bounding box associated with the cube texture
  62928. * When defined, the cubemap will switch to local mode
  62929. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62930. * @example https://www.babylonjs-playground.com/#RNASML
  62931. */
  62932. set: function (value) {
  62933. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62934. return;
  62935. }
  62936. this._boundingBoxSize = value;
  62937. var scene = this.getScene();
  62938. if (scene) {
  62939. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62940. }
  62941. },
  62942. enumerable: true,
  62943. configurable: true
  62944. });
  62945. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62946. /**
  62947. * Gets texture matrix rotation angle around Y axis radians.
  62948. */
  62949. get: function () {
  62950. return this._rotationY;
  62951. },
  62952. /**
  62953. * Sets texture matrix rotation angle around Y axis in radians.
  62954. */
  62955. set: function (value) {
  62956. this._rotationY = value;
  62957. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62958. },
  62959. enumerable: true,
  62960. configurable: true
  62961. });
  62962. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62963. var rootUrlKey = "";
  62964. files.forEach(function (url) { return rootUrlKey += url; });
  62965. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62966. };
  62967. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62968. if (forcedExtension === void 0) { forcedExtension = null; }
  62969. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62970. };
  62971. // Methods
  62972. CubeTexture.prototype.delayLoad = function () {
  62973. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62974. return;
  62975. }
  62976. var scene = this.getScene();
  62977. if (!scene) {
  62978. return;
  62979. }
  62980. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62981. this._texture = this._getFromCache(this.url, this._noMipmap);
  62982. if (!this._texture) {
  62983. if (this._prefiltered) {
  62984. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62985. }
  62986. else {
  62987. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62988. }
  62989. }
  62990. };
  62991. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62992. return this._textureMatrix;
  62993. };
  62994. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62995. this._textureMatrix = value;
  62996. };
  62997. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62998. var texture = BABYLON.SerializationHelper.Parse(function () {
  62999. var prefiltered = false;
  63000. if (parsedTexture.prefiltered) {
  63001. prefiltered = parsedTexture.prefiltered;
  63002. }
  63003. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63004. }, parsedTexture, scene);
  63005. // Local Cubemaps
  63006. if (parsedTexture.boundingBoxPosition) {
  63007. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63008. }
  63009. if (parsedTexture.boundingBoxSize) {
  63010. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63011. }
  63012. // Animations
  63013. if (parsedTexture.animations) {
  63014. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63015. var parsedAnimation = parsedTexture.animations[animationIndex];
  63016. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63017. }
  63018. }
  63019. return texture;
  63020. };
  63021. CubeTexture.prototype.clone = function () {
  63022. var _this = this;
  63023. return BABYLON.SerializationHelper.Clone(function () {
  63024. var scene = _this.getScene();
  63025. if (!scene) {
  63026. return _this;
  63027. }
  63028. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63029. }, this);
  63030. };
  63031. __decorate([
  63032. BABYLON.serialize("rotationY")
  63033. ], CubeTexture.prototype, "_rotationY", void 0);
  63034. return CubeTexture;
  63035. }(BABYLON.BaseTexture));
  63036. BABYLON.CubeTexture = CubeTexture;
  63037. })(BABYLON || (BABYLON = {}));
  63038. //# sourceMappingURL=babylon.cubeTexture.js.map
  63039. var BABYLON;
  63040. (function (BABYLON) {
  63041. var RenderTargetTexture = /** @class */ (function (_super) {
  63042. __extends(RenderTargetTexture, _super);
  63043. /**
  63044. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63045. * or used a shadow, depth texture...
  63046. * @param name The friendly name of the texture
  63047. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  63048. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63049. * @param generateMipMaps True if mip maps need to be generated after render.
  63050. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63051. * @param type The type of the buffer in the RTT (int, half float, float...)
  63052. * @param isCube True if a cube texture needs to be created
  63053. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63054. * @param generateDepthBuffer True to generate a depth buffer
  63055. * @param generateStencilBuffer True to generate a stencil buffer
  63056. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63057. */
  63058. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63059. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63060. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63061. if (isCube === void 0) { isCube = false; }
  63062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63063. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63064. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63065. if (isMulti === void 0) { isMulti = false; }
  63066. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63067. _this.isCube = isCube;
  63068. /**
  63069. * Use this list to define the list of mesh you want to render.
  63070. */
  63071. _this.renderList = new Array();
  63072. _this.renderParticles = true;
  63073. _this.renderSprites = false;
  63074. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63075. _this.ignoreCameraViewport = false;
  63076. // Events
  63077. /**
  63078. * An event triggered when the texture is unbind.
  63079. */
  63080. _this.onBeforeBindObservable = new BABYLON.Observable();
  63081. /**
  63082. * An event triggered when the texture is unbind.
  63083. */
  63084. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63085. /**
  63086. * An event triggered before rendering the texture
  63087. */
  63088. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63089. /**
  63090. * An event triggered after rendering the texture
  63091. */
  63092. _this.onAfterRenderObservable = new BABYLON.Observable();
  63093. /**
  63094. * An event triggered after the texture clear
  63095. */
  63096. _this.onClearObservable = new BABYLON.Observable();
  63097. _this._currentRefreshId = -1;
  63098. _this._refreshRate = 1;
  63099. _this._samples = 1;
  63100. /**
  63101. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63102. * It must define where the camera used to render the texture is set
  63103. */
  63104. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63105. scene = _this.getScene();
  63106. if (!scene) {
  63107. return _this;
  63108. }
  63109. _this._engine = scene.getEngine();
  63110. _this.name = name;
  63111. _this.isRenderTarget = true;
  63112. _this._initialSizeParameter = size;
  63113. _this._processSizeParameter(size);
  63114. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63115. });
  63116. _this._generateMipMaps = generateMipMaps ? true : false;
  63117. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63118. // Rendering groups
  63119. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63120. if (isMulti) {
  63121. return _this;
  63122. }
  63123. _this._renderTargetOptions = {
  63124. generateMipMaps: generateMipMaps,
  63125. type: type,
  63126. samplingMode: samplingMode,
  63127. generateDepthBuffer: generateDepthBuffer,
  63128. generateStencilBuffer: generateStencilBuffer
  63129. };
  63130. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63131. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63132. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63133. }
  63134. if (isCube) {
  63135. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63136. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63137. _this._textureMatrix = BABYLON.Matrix.Identity();
  63138. }
  63139. else {
  63140. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63141. }
  63142. return _this;
  63143. }
  63144. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63145. get: function () {
  63146. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63147. },
  63148. enumerable: true,
  63149. configurable: true
  63150. });
  63151. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63152. get: function () {
  63153. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63154. },
  63155. enumerable: true,
  63156. configurable: true
  63157. });
  63158. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63159. get: function () {
  63160. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63161. },
  63162. enumerable: true,
  63163. configurable: true
  63164. });
  63165. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63166. set: function (callback) {
  63167. if (this._onAfterUnbindObserver) {
  63168. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63169. }
  63170. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63171. },
  63172. enumerable: true,
  63173. configurable: true
  63174. });
  63175. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63176. set: function (callback) {
  63177. if (this._onBeforeRenderObserver) {
  63178. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63179. }
  63180. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63181. },
  63182. enumerable: true,
  63183. configurable: true
  63184. });
  63185. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63186. set: function (callback) {
  63187. if (this._onAfterRenderObserver) {
  63188. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63189. }
  63190. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63191. },
  63192. enumerable: true,
  63193. configurable: true
  63194. });
  63195. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63196. set: function (callback) {
  63197. if (this._onClearObserver) {
  63198. this.onClearObservable.remove(this._onClearObserver);
  63199. }
  63200. this._onClearObserver = this.onClearObservable.add(callback);
  63201. },
  63202. enumerable: true,
  63203. configurable: true
  63204. });
  63205. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63206. get: function () {
  63207. return this._renderTargetOptions;
  63208. },
  63209. enumerable: true,
  63210. configurable: true
  63211. });
  63212. RenderTargetTexture.prototype._onRatioRescale = function () {
  63213. if (this._sizeRatio) {
  63214. this.resize(this._initialSizeParameter);
  63215. }
  63216. };
  63217. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63218. get: function () {
  63219. return this._boundingBoxSize;
  63220. },
  63221. /**
  63222. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63223. * When defined, the cubemap will switch to local mode
  63224. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63225. * @example https://www.babylonjs-playground.com/#RNASML
  63226. */
  63227. set: function (value) {
  63228. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63229. return;
  63230. }
  63231. this._boundingBoxSize = value;
  63232. var scene = this.getScene();
  63233. if (scene) {
  63234. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63235. }
  63236. },
  63237. enumerable: true,
  63238. configurable: true
  63239. });
  63240. /**
  63241. * Creates a depth stencil texture.
  63242. * This is only available in WebGL 2 or with the depth texture extension available.
  63243. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63244. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63245. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63246. */
  63247. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63248. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63249. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63250. if (generateStencil === void 0) { generateStencil = false; }
  63251. if (!this.getScene()) {
  63252. return;
  63253. }
  63254. var engine = this.getScene().getEngine();
  63255. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63256. bilinearFiltering: bilinearFiltering,
  63257. comparisonFunction: comparisonFunction,
  63258. generateStencil: generateStencil,
  63259. isCube: this.isCube
  63260. });
  63261. engine.setFrameBufferDepthStencilTexture(this);
  63262. };
  63263. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63264. if (size.ratio) {
  63265. this._sizeRatio = size.ratio;
  63266. this._size = {
  63267. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63268. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63269. };
  63270. }
  63271. else {
  63272. this._size = size;
  63273. }
  63274. };
  63275. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63276. get: function () {
  63277. return this._samples;
  63278. },
  63279. set: function (value) {
  63280. if (this._samples === value) {
  63281. return;
  63282. }
  63283. var scene = this.getScene();
  63284. if (!scene) {
  63285. return;
  63286. }
  63287. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63293. this._currentRefreshId = -1;
  63294. };
  63295. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63296. get: function () {
  63297. return this._refreshRate;
  63298. },
  63299. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63300. set: function (value) {
  63301. this._refreshRate = value;
  63302. this.resetRefreshCounter();
  63303. },
  63304. enumerable: true,
  63305. configurable: true
  63306. });
  63307. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63308. if (!this._postProcessManager) {
  63309. var scene = this.getScene();
  63310. if (!scene) {
  63311. return;
  63312. }
  63313. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63314. this._postProcesses = new Array();
  63315. }
  63316. this._postProcesses.push(postProcess);
  63317. this._postProcesses[0].autoClear = false;
  63318. };
  63319. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63320. if (!this._postProcesses) {
  63321. return;
  63322. }
  63323. if (dispose) {
  63324. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63325. var postProcess = _a[_i];
  63326. postProcess.dispose();
  63327. }
  63328. }
  63329. this._postProcesses = [];
  63330. };
  63331. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63332. if (!this._postProcesses) {
  63333. return;
  63334. }
  63335. var index = this._postProcesses.indexOf(postProcess);
  63336. if (index === -1) {
  63337. return;
  63338. }
  63339. this._postProcesses.splice(index, 1);
  63340. if (this._postProcesses.length > 0) {
  63341. this._postProcesses[0].autoClear = false;
  63342. }
  63343. };
  63344. RenderTargetTexture.prototype._shouldRender = function () {
  63345. if (this._currentRefreshId === -1) { // At least render once
  63346. this._currentRefreshId = 1;
  63347. return true;
  63348. }
  63349. if (this.refreshRate === this._currentRefreshId) {
  63350. this._currentRefreshId = 1;
  63351. return true;
  63352. }
  63353. this._currentRefreshId++;
  63354. return false;
  63355. };
  63356. RenderTargetTexture.prototype.getRenderSize = function () {
  63357. if (this._size.width) {
  63358. return this._size.width;
  63359. }
  63360. return this._size;
  63361. };
  63362. RenderTargetTexture.prototype.getRenderWidth = function () {
  63363. if (this._size.width) {
  63364. return this._size.width;
  63365. }
  63366. return this._size;
  63367. };
  63368. RenderTargetTexture.prototype.getRenderHeight = function () {
  63369. if (this._size.width) {
  63370. return this._size.height;
  63371. }
  63372. return this._size;
  63373. };
  63374. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63375. get: function () {
  63376. return true;
  63377. },
  63378. enumerable: true,
  63379. configurable: true
  63380. });
  63381. RenderTargetTexture.prototype.scale = function (ratio) {
  63382. var newSize = this.getRenderSize() * ratio;
  63383. this.resize(newSize);
  63384. };
  63385. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63386. if (this.isCube) {
  63387. return this._textureMatrix;
  63388. }
  63389. return _super.prototype.getReflectionTextureMatrix.call(this);
  63390. };
  63391. RenderTargetTexture.prototype.resize = function (size) {
  63392. this.releaseInternalTexture();
  63393. var scene = this.getScene();
  63394. if (!scene) {
  63395. return;
  63396. }
  63397. this._processSizeParameter(size);
  63398. if (this.isCube) {
  63399. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63400. }
  63401. else {
  63402. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63403. }
  63404. };
  63405. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63406. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63407. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63408. var scene = this.getScene();
  63409. if (!scene) {
  63410. return;
  63411. }
  63412. var engine = scene.getEngine();
  63413. if (this.useCameraPostProcesses !== undefined) {
  63414. useCameraPostProcess = this.useCameraPostProcesses;
  63415. }
  63416. if (this._waitingRenderList) {
  63417. this.renderList = [];
  63418. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63419. var id = this._waitingRenderList[index];
  63420. var mesh_1 = scene.getMeshByID(id);
  63421. if (mesh_1) {
  63422. this.renderList.push(mesh_1);
  63423. }
  63424. }
  63425. delete this._waitingRenderList;
  63426. }
  63427. // Is predicate defined?
  63428. if (this.renderListPredicate) {
  63429. if (this.renderList) {
  63430. this.renderList.splice(0); // Clear previous renderList
  63431. }
  63432. else {
  63433. this.renderList = [];
  63434. }
  63435. var scene = this.getScene();
  63436. if (!scene) {
  63437. return;
  63438. }
  63439. var sceneMeshes = scene.meshes;
  63440. for (var index = 0; index < sceneMeshes.length; index++) {
  63441. var mesh = sceneMeshes[index];
  63442. if (this.renderListPredicate(mesh)) {
  63443. this.renderList.push(mesh);
  63444. }
  63445. }
  63446. }
  63447. this.onBeforeBindObservable.notifyObservers(this);
  63448. // Set custom projection.
  63449. // Needs to be before binding to prevent changing the aspect ratio.
  63450. var camera;
  63451. if (this.activeCamera) {
  63452. camera = this.activeCamera;
  63453. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63454. if (this.activeCamera !== scene.activeCamera) {
  63455. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63456. }
  63457. }
  63458. else {
  63459. camera = scene.activeCamera;
  63460. if (camera) {
  63461. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63462. }
  63463. }
  63464. // Prepare renderingManager
  63465. this._renderingManager.reset();
  63466. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63467. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63468. var sceneRenderId = scene.getRenderId();
  63469. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63470. var mesh = currentRenderList[meshIndex];
  63471. if (mesh) {
  63472. if (!mesh.isReady(this.refreshRate === 0)) {
  63473. this.resetRefreshCounter();
  63474. continue;
  63475. }
  63476. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63477. var isMasked = void 0;
  63478. if (!this.renderList && camera) {
  63479. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63480. }
  63481. else {
  63482. isMasked = false;
  63483. }
  63484. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63485. mesh._activate(sceneRenderId);
  63486. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63487. var subMesh = mesh.subMeshes[subIndex];
  63488. scene._activeIndices.addCount(subMesh.indexCount, false);
  63489. this._renderingManager.dispatch(subMesh, mesh);
  63490. }
  63491. }
  63492. }
  63493. }
  63494. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63495. var particleSystem = scene.particleSystems[particleIndex];
  63496. var emitter = particleSystem.emitter;
  63497. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63498. continue;
  63499. }
  63500. if (currentRenderList.indexOf(emitter) >= 0) {
  63501. this._renderingManager.dispatchParticles(particleSystem);
  63502. }
  63503. }
  63504. if (this.isCube) {
  63505. for (var face = 0; face < 6; face++) {
  63506. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63507. scene.incrementRenderId();
  63508. scene.resetCachedMaterial();
  63509. }
  63510. }
  63511. else {
  63512. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63513. }
  63514. this.onAfterUnbindObservable.notifyObservers(this);
  63515. if (scene.activeCamera) {
  63516. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63517. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63518. }
  63519. engine.setViewport(scene.activeCamera.viewport);
  63520. }
  63521. scene.resetCachedMaterial();
  63522. };
  63523. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63524. var minimum = 128;
  63525. var x = renderDimension * scale;
  63526. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63527. // Ensure we don't exceed the render dimension (while staying POT)
  63528. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63529. };
  63530. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63531. var _this = this;
  63532. if (!this._texture) {
  63533. return;
  63534. }
  63535. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63536. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63537. });
  63538. };
  63539. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63540. var scene = this.getScene();
  63541. if (!scene) {
  63542. return;
  63543. }
  63544. var engine = scene.getEngine();
  63545. if (!this._texture) {
  63546. return;
  63547. }
  63548. // Bind
  63549. if (this._postProcessManager) {
  63550. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63551. }
  63552. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63553. if (this._texture) {
  63554. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63555. }
  63556. }
  63557. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63558. // Clear
  63559. if (this.onClearObservable.hasObservers()) {
  63560. this.onClearObservable.notifyObservers(engine);
  63561. }
  63562. else {
  63563. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63564. }
  63565. if (!this._doNotChangeAspectRatio) {
  63566. scene.updateTransformMatrix(true);
  63567. }
  63568. // Render
  63569. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63570. if (this._postProcessManager) {
  63571. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63572. }
  63573. else if (useCameraPostProcess) {
  63574. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63575. }
  63576. if (!this._doNotChangeAspectRatio) {
  63577. scene.updateTransformMatrix(true);
  63578. }
  63579. // Dump ?
  63580. if (dumpForDebug) {
  63581. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63582. }
  63583. // Unbind
  63584. if (!this.isCube || faceIndex === 5) {
  63585. if (this.isCube) {
  63586. if (faceIndex === 5) {
  63587. engine.generateMipMapsForCubemap(this._texture);
  63588. }
  63589. }
  63590. this.unbindFrameBuffer(engine, faceIndex);
  63591. }
  63592. else {
  63593. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63594. }
  63595. };
  63596. /**
  63597. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63598. * This allowed control for front to back rendering or reversly depending of the special needs.
  63599. *
  63600. * @param renderingGroupId The rendering group id corresponding to its index
  63601. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63602. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63603. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63604. */
  63605. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63606. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63607. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63608. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63609. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63610. };
  63611. /**
  63612. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63613. *
  63614. * @param renderingGroupId The rendering group id corresponding to its index
  63615. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63616. */
  63617. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63618. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63619. };
  63620. RenderTargetTexture.prototype.clone = function () {
  63621. var textureSize = this.getSize();
  63622. 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);
  63623. // Base texture
  63624. newTexture.hasAlpha = this.hasAlpha;
  63625. newTexture.level = this.level;
  63626. // RenderTarget Texture
  63627. newTexture.coordinatesMode = this.coordinatesMode;
  63628. if (this.renderList) {
  63629. newTexture.renderList = this.renderList.slice(0);
  63630. }
  63631. return newTexture;
  63632. };
  63633. RenderTargetTexture.prototype.serialize = function () {
  63634. if (!this.name) {
  63635. return null;
  63636. }
  63637. var serializationObject = _super.prototype.serialize.call(this);
  63638. serializationObject.renderTargetSize = this.getRenderSize();
  63639. serializationObject.renderList = [];
  63640. if (this.renderList) {
  63641. for (var index = 0; index < this.renderList.length; index++) {
  63642. serializationObject.renderList.push(this.renderList[index].id);
  63643. }
  63644. }
  63645. return serializationObject;
  63646. };
  63647. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63648. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63649. var objBuffer = this.getInternalTexture();
  63650. var scene = this.getScene();
  63651. if (objBuffer && scene) {
  63652. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63653. }
  63654. };
  63655. RenderTargetTexture.prototype.dispose = function () {
  63656. if (this._postProcessManager) {
  63657. this._postProcessManager.dispose();
  63658. this._postProcessManager = null;
  63659. }
  63660. this.clearPostProcesses(true);
  63661. if (this._resizeObserver) {
  63662. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63663. this._resizeObserver = null;
  63664. }
  63665. this.renderList = null;
  63666. // Remove from custom render targets
  63667. var scene = this.getScene();
  63668. if (!scene) {
  63669. return;
  63670. }
  63671. var index = scene.customRenderTargets.indexOf(this);
  63672. if (index >= 0) {
  63673. scene.customRenderTargets.splice(index, 1);
  63674. }
  63675. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63676. var camera = _a[_i];
  63677. index = camera.customRenderTargets.indexOf(this);
  63678. if (index >= 0) {
  63679. camera.customRenderTargets.splice(index, 1);
  63680. }
  63681. }
  63682. _super.prototype.dispose.call(this);
  63683. };
  63684. RenderTargetTexture.prototype._rebuild = function () {
  63685. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63686. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63687. }
  63688. if (this._postProcessManager) {
  63689. this._postProcessManager._rebuild();
  63690. }
  63691. };
  63692. /**
  63693. * Clear the info related to rendering groups preventing retention point in material dispose.
  63694. */
  63695. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63696. if (this._renderingManager) {
  63697. this._renderingManager.freeRenderingGroups();
  63698. }
  63699. };
  63700. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63701. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63702. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63703. return RenderTargetTexture;
  63704. }(BABYLON.Texture));
  63705. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63706. })(BABYLON || (BABYLON = {}));
  63707. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63708. var BABYLON;
  63709. (function (BABYLON) {
  63710. ;
  63711. var MultiRenderTarget = /** @class */ (function (_super) {
  63712. __extends(MultiRenderTarget, _super);
  63713. function MultiRenderTarget(name, size, count, scene, options) {
  63714. var _this = this;
  63715. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63716. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63717. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63718. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63719. _this._engine = scene.getEngine();
  63720. if (!_this.isSupported) {
  63721. _this.dispose();
  63722. return;
  63723. }
  63724. var types = [];
  63725. var samplingModes = [];
  63726. for (var i = 0; i < count; i++) {
  63727. if (options && options.types && options.types[i] !== undefined) {
  63728. types.push(options.types[i]);
  63729. }
  63730. else {
  63731. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63732. }
  63733. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63734. samplingModes.push(options.samplingModes[i]);
  63735. }
  63736. else {
  63737. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63738. }
  63739. }
  63740. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63741. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63742. _this._size = size;
  63743. _this._multiRenderTargetOptions = {
  63744. samplingModes: samplingModes,
  63745. generateMipMaps: generateMipMaps,
  63746. generateDepthBuffer: generateDepthBuffer,
  63747. generateStencilBuffer: generateStencilBuffer,
  63748. generateDepthTexture: generateDepthTexture,
  63749. types: types,
  63750. textureCount: count
  63751. };
  63752. _this._createInternalTextures();
  63753. _this._createTextures();
  63754. return _this;
  63755. }
  63756. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63757. get: function () {
  63758. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63759. },
  63760. enumerable: true,
  63761. configurable: true
  63762. });
  63763. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63764. get: function () {
  63765. return this._textures;
  63766. },
  63767. enumerable: true,
  63768. configurable: true
  63769. });
  63770. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63771. get: function () {
  63772. return this._textures[this._textures.length - 1];
  63773. },
  63774. enumerable: true,
  63775. configurable: true
  63776. });
  63777. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63778. set: function (wrap) {
  63779. if (this._textures) {
  63780. for (var i = 0; i < this._textures.length; i++) {
  63781. this._textures[i].wrapU = wrap;
  63782. }
  63783. }
  63784. },
  63785. enumerable: true,
  63786. configurable: true
  63787. });
  63788. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63789. set: function (wrap) {
  63790. if (this._textures) {
  63791. for (var i = 0; i < this._textures.length; i++) {
  63792. this._textures[i].wrapV = wrap;
  63793. }
  63794. }
  63795. },
  63796. enumerable: true,
  63797. configurable: true
  63798. });
  63799. MultiRenderTarget.prototype._rebuild = function () {
  63800. this.releaseInternalTextures();
  63801. this._createInternalTextures();
  63802. for (var i = 0; i < this._internalTextures.length; i++) {
  63803. var texture = this._textures[i];
  63804. texture._texture = this._internalTextures[i];
  63805. }
  63806. // Keeps references to frame buffer and stencil/depth buffer
  63807. this._texture = this._internalTextures[0];
  63808. };
  63809. MultiRenderTarget.prototype._createInternalTextures = function () {
  63810. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63811. };
  63812. MultiRenderTarget.prototype._createTextures = function () {
  63813. this._textures = [];
  63814. for (var i = 0; i < this._internalTextures.length; i++) {
  63815. var texture = new BABYLON.Texture(null, this.getScene());
  63816. texture._texture = this._internalTextures[i];
  63817. this._textures.push(texture);
  63818. }
  63819. // Keeps references to frame buffer and stencil/depth buffer
  63820. this._texture = this._internalTextures[0];
  63821. };
  63822. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63823. get: function () {
  63824. return this._samples;
  63825. },
  63826. set: function (value) {
  63827. if (this._samples === value) {
  63828. return;
  63829. }
  63830. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63831. },
  63832. enumerable: true,
  63833. configurable: true
  63834. });
  63835. MultiRenderTarget.prototype.resize = function (size) {
  63836. this.releaseInternalTextures();
  63837. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63838. this._createInternalTextures();
  63839. };
  63840. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63841. var _this = this;
  63842. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63843. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63844. });
  63845. };
  63846. MultiRenderTarget.prototype.dispose = function () {
  63847. this.releaseInternalTextures();
  63848. _super.prototype.dispose.call(this);
  63849. };
  63850. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63851. if (!this._internalTextures) {
  63852. return;
  63853. }
  63854. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63855. if (this._internalTextures[i] !== undefined) {
  63856. this._internalTextures[i].dispose();
  63857. this._internalTextures.splice(i, 1);
  63858. }
  63859. }
  63860. };
  63861. return MultiRenderTarget;
  63862. }(BABYLON.RenderTargetTexture));
  63863. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63864. })(BABYLON || (BABYLON = {}));
  63865. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63866. var BABYLON;
  63867. (function (BABYLON) {
  63868. var MirrorTexture = /** @class */ (function (_super) {
  63869. __extends(MirrorTexture, _super);
  63870. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63871. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63873. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63874. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63875. _this.scene = scene;
  63876. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63877. _this._transformMatrix = BABYLON.Matrix.Zero();
  63878. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63879. _this._adaptiveBlurKernel = 0;
  63880. _this._blurKernelX = 0;
  63881. _this._blurKernelY = 0;
  63882. _this._blurRatio = 1.0;
  63883. _this.ignoreCameraViewport = true;
  63884. _this._updateGammaSpace();
  63885. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63886. _this._updateGammaSpace;
  63887. });
  63888. _this.onBeforeRenderObservable.add(function () {
  63889. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63890. _this._savedViewMatrix = scene.getViewMatrix();
  63891. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63892. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63893. scene.clipPlane = _this.mirrorPlane;
  63894. scene.getEngine().cullBackFaces = false;
  63895. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63896. });
  63897. _this.onAfterRenderObservable.add(function () {
  63898. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63899. scene.getEngine().cullBackFaces = true;
  63900. scene._mirroredCameraPosition = null;
  63901. delete scene.clipPlane;
  63902. });
  63903. return _this;
  63904. }
  63905. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63906. get: function () {
  63907. return this._blurRatio;
  63908. },
  63909. set: function (value) {
  63910. if (this._blurRatio === value) {
  63911. return;
  63912. }
  63913. this._blurRatio = value;
  63914. this._preparePostProcesses();
  63915. },
  63916. enumerable: true,
  63917. configurable: true
  63918. });
  63919. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63920. set: function (value) {
  63921. this._adaptiveBlurKernel = value;
  63922. this._autoComputeBlurKernel();
  63923. },
  63924. enumerable: true,
  63925. configurable: true
  63926. });
  63927. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63928. set: function (value) {
  63929. this.blurKernelX = value;
  63930. this.blurKernelY = value;
  63931. },
  63932. enumerable: true,
  63933. configurable: true
  63934. });
  63935. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63936. get: function () {
  63937. return this._blurKernelX;
  63938. },
  63939. set: function (value) {
  63940. if (this._blurKernelX === value) {
  63941. return;
  63942. }
  63943. this._blurKernelX = value;
  63944. this._preparePostProcesses();
  63945. },
  63946. enumerable: true,
  63947. configurable: true
  63948. });
  63949. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63950. get: function () {
  63951. return this._blurKernelY;
  63952. },
  63953. set: function (value) {
  63954. if (this._blurKernelY === value) {
  63955. return;
  63956. }
  63957. this._blurKernelY = value;
  63958. this._preparePostProcesses();
  63959. },
  63960. enumerable: true,
  63961. configurable: true
  63962. });
  63963. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63964. var engine = this.getScene().getEngine();
  63965. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63966. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63967. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63968. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63969. };
  63970. MirrorTexture.prototype._onRatioRescale = function () {
  63971. if (this._sizeRatio) {
  63972. this.resize(this._initialSizeParameter);
  63973. if (!this._adaptiveBlurKernel) {
  63974. this._preparePostProcesses();
  63975. }
  63976. }
  63977. if (this._adaptiveBlurKernel) {
  63978. this._autoComputeBlurKernel();
  63979. }
  63980. };
  63981. MirrorTexture.prototype._updateGammaSpace = function () {
  63982. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63983. };
  63984. MirrorTexture.prototype._preparePostProcesses = function () {
  63985. this.clearPostProcesses(true);
  63986. if (this._blurKernelX && this._blurKernelY) {
  63987. var engine = this.getScene().getEngine();
  63988. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63989. 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);
  63990. this._blurX.autoClear = false;
  63991. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63992. this._blurX.inputTexture = this._texture;
  63993. }
  63994. else {
  63995. this._blurX.alwaysForcePOT = true;
  63996. }
  63997. 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);
  63998. this._blurY.autoClear = false;
  63999. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64000. this.addPostProcess(this._blurX);
  64001. this.addPostProcess(this._blurY);
  64002. }
  64003. else {
  64004. if (this._blurY) {
  64005. this.removePostProcess(this._blurY);
  64006. this._blurY.dispose();
  64007. this._blurY = null;
  64008. }
  64009. if (this._blurX) {
  64010. this.removePostProcess(this._blurX);
  64011. this._blurX.dispose();
  64012. this._blurX = null;
  64013. }
  64014. }
  64015. };
  64016. MirrorTexture.prototype.clone = function () {
  64017. var scene = this.getScene();
  64018. if (!scene) {
  64019. return this;
  64020. }
  64021. var textureSize = this.getSize();
  64022. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64023. // Base texture
  64024. newTexture.hasAlpha = this.hasAlpha;
  64025. newTexture.level = this.level;
  64026. // Mirror Texture
  64027. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64028. if (this.renderList) {
  64029. newTexture.renderList = this.renderList.slice(0);
  64030. }
  64031. return newTexture;
  64032. };
  64033. MirrorTexture.prototype.serialize = function () {
  64034. if (!this.name) {
  64035. return null;
  64036. }
  64037. var serializationObject = _super.prototype.serialize.call(this);
  64038. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64039. return serializationObject;
  64040. };
  64041. MirrorTexture.prototype.dispose = function () {
  64042. _super.prototype.dispose.call(this);
  64043. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64044. };
  64045. return MirrorTexture;
  64046. }(BABYLON.RenderTargetTexture));
  64047. BABYLON.MirrorTexture = MirrorTexture;
  64048. })(BABYLON || (BABYLON = {}));
  64049. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64050. var BABYLON;
  64051. (function (BABYLON) {
  64052. /**
  64053. * Creates a refraction texture used by refraction channel of the standard material.
  64054. * @param name the texture name
  64055. * @param size size of the underlying texture
  64056. * @param scene root scene
  64057. */
  64058. var RefractionTexture = /** @class */ (function (_super) {
  64059. __extends(RefractionTexture, _super);
  64060. function RefractionTexture(name, size, scene, generateMipMaps) {
  64061. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64062. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64063. _this.depth = 2.0;
  64064. _this.onBeforeRenderObservable.add(function () {
  64065. scene.clipPlane = _this.refractionPlane;
  64066. });
  64067. _this.onAfterRenderObservable.add(function () {
  64068. delete scene.clipPlane;
  64069. });
  64070. return _this;
  64071. }
  64072. RefractionTexture.prototype.clone = function () {
  64073. var scene = this.getScene();
  64074. if (!scene) {
  64075. return this;
  64076. }
  64077. var textureSize = this.getSize();
  64078. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64079. // Base texture
  64080. newTexture.hasAlpha = this.hasAlpha;
  64081. newTexture.level = this.level;
  64082. // Refraction Texture
  64083. newTexture.refractionPlane = this.refractionPlane.clone();
  64084. if (this.renderList) {
  64085. newTexture.renderList = this.renderList.slice(0);
  64086. }
  64087. newTexture.depth = this.depth;
  64088. return newTexture;
  64089. };
  64090. RefractionTexture.prototype.serialize = function () {
  64091. if (!this.name) {
  64092. return null;
  64093. }
  64094. var serializationObject = _super.prototype.serialize.call(this);
  64095. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64096. serializationObject.depth = this.depth;
  64097. return serializationObject;
  64098. };
  64099. return RefractionTexture;
  64100. }(BABYLON.RenderTargetTexture));
  64101. BABYLON.RefractionTexture = RefractionTexture;
  64102. })(BABYLON || (BABYLON = {}));
  64103. //# sourceMappingURL=babylon.refractionTexture.js.map
  64104. var BABYLON;
  64105. (function (BABYLON) {
  64106. /**
  64107. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64108. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64109. */
  64110. var DynamicTexture = /** @class */ (function (_super) {
  64111. __extends(DynamicTexture, _super);
  64112. /**
  64113. * Creates a {BABYLON.DynamicTexture}
  64114. * @param name defines the name of the texture
  64115. * @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
  64116. * @param scene defines the scene where you want the texture
  64117. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64118. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64119. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64120. */
  64121. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64122. if (scene === void 0) { scene = null; }
  64123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64124. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64125. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64126. _this.name = name;
  64127. _this._engine = _this.getScene().getEngine();
  64128. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64129. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64130. _this._generateMipMaps = generateMipMaps;
  64131. if (options.getContext) {
  64132. _this._canvas = options;
  64133. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64134. }
  64135. else {
  64136. _this._canvas = document.createElement("canvas");
  64137. if (options.width || options.width === 0) {
  64138. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64139. }
  64140. else {
  64141. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64142. }
  64143. }
  64144. var textureSize = _this.getSize();
  64145. _this._canvas.width = textureSize.width;
  64146. _this._canvas.height = textureSize.height;
  64147. _this._context = _this._canvas.getContext("2d");
  64148. return _this;
  64149. }
  64150. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64151. /**
  64152. * Gets the current state of canRescale
  64153. */
  64154. get: function () {
  64155. return true;
  64156. },
  64157. enumerable: true,
  64158. configurable: true
  64159. });
  64160. DynamicTexture.prototype._recreate = function (textureSize) {
  64161. this._canvas.width = textureSize.width;
  64162. this._canvas.height = textureSize.height;
  64163. this.releaseInternalTexture();
  64164. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64165. };
  64166. /**
  64167. * Scales the texture
  64168. * @param ratio the scale factor to apply to both width and height
  64169. */
  64170. DynamicTexture.prototype.scale = function (ratio) {
  64171. var textureSize = this.getSize();
  64172. textureSize.width *= ratio;
  64173. textureSize.height *= ratio;
  64174. this._recreate(textureSize);
  64175. };
  64176. /**
  64177. * Resizes the texture
  64178. * @param width the new width
  64179. * @param height the new height
  64180. */
  64181. DynamicTexture.prototype.scaleTo = function (width, height) {
  64182. var textureSize = this.getSize();
  64183. textureSize.width = width;
  64184. textureSize.height = height;
  64185. this._recreate(textureSize);
  64186. };
  64187. /**
  64188. * Gets the context of the canvas used by the texture
  64189. * @returns the canvas context of the dynamic texture
  64190. */
  64191. DynamicTexture.prototype.getContext = function () {
  64192. return this._context;
  64193. };
  64194. /**
  64195. * Clears the texture
  64196. */
  64197. DynamicTexture.prototype.clear = function () {
  64198. var size = this.getSize();
  64199. this._context.fillRect(0, 0, size.width, size.height);
  64200. };
  64201. /**
  64202. * Updates the texture
  64203. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64204. */
  64205. DynamicTexture.prototype.update = function (invertY) {
  64206. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64207. };
  64208. /**
  64209. * Draws text onto the texture
  64210. * @param text defines the text to be drawn
  64211. * @param x defines the placement of the text from the left
  64212. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64213. * @param font defines the font to be used with font-style, font-size, font-name
  64214. * @param color defines the color used for the text
  64215. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64216. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64217. * @param update defines whether texture is immediately update (default is true)
  64218. */
  64219. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64220. if (update === void 0) { update = true; }
  64221. var size = this.getSize();
  64222. if (clearColor) {
  64223. this._context.fillStyle = clearColor;
  64224. this._context.fillRect(0, 0, size.width, size.height);
  64225. }
  64226. this._context.font = font;
  64227. if (x === null || x === undefined) {
  64228. var textSize = this._context.measureText(text);
  64229. x = (size.width - textSize.width) / 2;
  64230. }
  64231. if (y === null || y === undefined) {
  64232. var fontSize = parseInt((font.replace(/\D/g, '')));
  64233. ;
  64234. y = (size.height / 2) + (fontSize / 3.65);
  64235. }
  64236. this._context.fillStyle = color;
  64237. this._context.fillText(text, x, y);
  64238. if (update) {
  64239. this.update(invertY);
  64240. }
  64241. };
  64242. /**
  64243. * Clones the texture
  64244. * @returns the clone of the texture.
  64245. */
  64246. DynamicTexture.prototype.clone = function () {
  64247. var scene = this.getScene();
  64248. if (!scene) {
  64249. return this;
  64250. }
  64251. var textureSize = this.getSize();
  64252. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64253. // Base texture
  64254. newTexture.hasAlpha = this.hasAlpha;
  64255. newTexture.level = this.level;
  64256. // Dynamic Texture
  64257. newTexture.wrapU = this.wrapU;
  64258. newTexture.wrapV = this.wrapV;
  64259. return newTexture;
  64260. };
  64261. /** @hidden */
  64262. DynamicTexture.prototype._rebuild = function () {
  64263. this.update();
  64264. };
  64265. return DynamicTexture;
  64266. }(BABYLON.Texture));
  64267. BABYLON.DynamicTexture = DynamicTexture;
  64268. })(BABYLON || (BABYLON = {}));
  64269. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64270. var BABYLON;
  64271. (function (BABYLON) {
  64272. var VideoTexture = /** @class */ (function (_super) {
  64273. __extends(VideoTexture, _super);
  64274. /**
  64275. * Creates a video texture.
  64276. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64277. * @param {string | null} name optional name, will detect from video source, if not defined
  64278. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64279. * @param {BABYLON.Scene} scene is obviously the current scene.
  64280. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64281. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64282. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64283. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64284. */
  64285. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64286. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64287. if (invertY === void 0) { invertY = false; }
  64288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64289. if (settings === void 0) { settings = {
  64290. autoPlay: true,
  64291. loop: true,
  64292. autoUpdateTexture: true,
  64293. }; }
  64294. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64295. _this._createInternalTexture = function () {
  64296. if (_this._texture != null) {
  64297. return;
  64298. }
  64299. if (!_this._engine.needPOTTextures ||
  64300. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64301. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64302. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64303. }
  64304. else {
  64305. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64306. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64307. _this._generateMipMaps = false;
  64308. }
  64309. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64310. _this._texture.isReady = true;
  64311. _this._updateInternalTexture();
  64312. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64313. _this.onLoadObservable.notifyObservers(_this);
  64314. }
  64315. };
  64316. _this.reset = function () {
  64317. if (_this._texture == null) {
  64318. return;
  64319. }
  64320. _this._texture.dispose();
  64321. _this._texture = null;
  64322. };
  64323. _this._updateInternalTexture = function (e) {
  64324. if (_this._texture == null || !_this._texture.isReady) {
  64325. return;
  64326. }
  64327. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64328. return;
  64329. }
  64330. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64331. };
  64332. _this._engine = _this.getScene().getEngine();
  64333. _this._generateMipMaps = generateMipMaps;
  64334. _this._samplingMode = samplingMode;
  64335. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64336. _this.name = name || _this._getName(src);
  64337. _this.video = _this._getVideo(src);
  64338. if (settings.autoPlay !== undefined) {
  64339. _this.video.autoplay = settings.autoPlay;
  64340. }
  64341. if (settings.loop !== undefined) {
  64342. _this.video.loop = settings.loop;
  64343. }
  64344. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64345. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64346. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64347. _this.video.addEventListener("emptied", _this.reset);
  64348. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64349. _this._createInternalTexture();
  64350. }
  64351. return _this;
  64352. }
  64353. VideoTexture.prototype._getName = function (src) {
  64354. if (src instanceof HTMLVideoElement) {
  64355. return src.currentSrc;
  64356. }
  64357. if (typeof src === "object") {
  64358. return src.toString();
  64359. }
  64360. return src;
  64361. };
  64362. ;
  64363. VideoTexture.prototype._getVideo = function (src) {
  64364. if (src instanceof HTMLVideoElement) {
  64365. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64366. return src;
  64367. }
  64368. var video = document.createElement("video");
  64369. if (typeof src === "string") {
  64370. BABYLON.Tools.SetCorsBehavior(src, video);
  64371. video.src = src;
  64372. }
  64373. else {
  64374. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64375. src.forEach(function (url) {
  64376. var source = document.createElement("source");
  64377. source.src = url;
  64378. video.appendChild(source);
  64379. });
  64380. }
  64381. return video;
  64382. };
  64383. ;
  64384. /**
  64385. * Internal method to initiate `update`.
  64386. */
  64387. VideoTexture.prototype._rebuild = function () {
  64388. this.update();
  64389. };
  64390. /**
  64391. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64392. */
  64393. VideoTexture.prototype.update = function () {
  64394. if (!this.autoUpdateTexture) {
  64395. // Expecting user to call `updateTexture` manually
  64396. return;
  64397. }
  64398. this.updateTexture(true);
  64399. };
  64400. /**
  64401. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64402. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64403. */
  64404. VideoTexture.prototype.updateTexture = function (isVisible) {
  64405. if (!isVisible) {
  64406. return;
  64407. }
  64408. if (this.video.paused) {
  64409. return;
  64410. }
  64411. this._updateInternalTexture();
  64412. };
  64413. /**
  64414. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64415. * @param url New url.
  64416. */
  64417. VideoTexture.prototype.updateURL = function (url) {
  64418. this.video.src = url;
  64419. };
  64420. VideoTexture.prototype.dispose = function () {
  64421. _super.prototype.dispose.call(this);
  64422. this.video.removeEventListener("canplay", this._createInternalTexture);
  64423. this.video.removeEventListener("paused", this._updateInternalTexture);
  64424. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64425. this.video.removeEventListener("emptied", this.reset);
  64426. this.video.pause();
  64427. };
  64428. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64429. var video = document.createElement("video");
  64430. var constraintsDeviceId;
  64431. if (constraints && constraints.deviceId) {
  64432. constraintsDeviceId = {
  64433. exact: constraints.deviceId,
  64434. };
  64435. }
  64436. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64437. if (navigator.mediaDevices) {
  64438. navigator.mediaDevices.getUserMedia({ video: constraints })
  64439. .then(function (stream) {
  64440. if (video.mozSrcObject !== undefined) {
  64441. // hack for Firefox < 19
  64442. video.mozSrcObject = stream;
  64443. }
  64444. else {
  64445. video.srcObject = stream;
  64446. }
  64447. var onPlaying = function () {
  64448. if (onReady) {
  64449. onReady(new VideoTexture("video", video, scene, true, true));
  64450. }
  64451. video.removeEventListener("playing", onPlaying);
  64452. };
  64453. video.addEventListener("playing", onPlaying);
  64454. video.play();
  64455. })
  64456. .catch(function (err) {
  64457. BABYLON.Tools.Error(err.name);
  64458. });
  64459. }
  64460. else {
  64461. navigator.getUserMedia =
  64462. navigator.getUserMedia ||
  64463. navigator.webkitGetUserMedia ||
  64464. navigator.mozGetUserMedia ||
  64465. navigator.msGetUserMedia;
  64466. if (navigator.getUserMedia) {
  64467. navigator.getUserMedia({
  64468. video: {
  64469. deviceId: constraintsDeviceId,
  64470. width: {
  64471. min: (constraints && constraints.minWidth) || 256,
  64472. max: (constraints && constraints.maxWidth) || 640,
  64473. },
  64474. height: {
  64475. min: (constraints && constraints.minHeight) || 256,
  64476. max: (constraints && constraints.maxHeight) || 480,
  64477. },
  64478. },
  64479. }, function (stream) {
  64480. if (video.mozSrcObject !== undefined) {
  64481. // hack for Firefox < 19
  64482. video.mozSrcObject = stream;
  64483. }
  64484. else {
  64485. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64486. }
  64487. video.play();
  64488. if (onReady) {
  64489. onReady(new VideoTexture("video", video, scene, true, true));
  64490. }
  64491. }, function (e) {
  64492. BABYLON.Tools.Error(e.name);
  64493. });
  64494. }
  64495. }
  64496. };
  64497. return VideoTexture;
  64498. }(BABYLON.Texture));
  64499. BABYLON.VideoTexture = VideoTexture;
  64500. })(BABYLON || (BABYLON = {}));
  64501. //# sourceMappingURL=babylon.videoTexture.js.map
  64502. var BABYLON;
  64503. (function (BABYLON) {
  64504. var RawTexture = /** @class */ (function (_super) {
  64505. __extends(RawTexture, _super);
  64506. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64507. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64508. if (invertY === void 0) { invertY = false; }
  64509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64510. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64511. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64512. _this.format = format;
  64513. _this._engine = scene.getEngine();
  64514. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64515. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64516. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64517. return _this;
  64518. }
  64519. RawTexture.prototype.update = function (data) {
  64520. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64521. };
  64522. // Statics
  64523. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64524. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64525. if (invertY === void 0) { invertY = false; }
  64526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64527. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64528. };
  64529. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64530. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64531. if (invertY === void 0) { invertY = false; }
  64532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64533. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64534. };
  64535. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64536. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64537. if (invertY === void 0) { invertY = false; }
  64538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64539. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64540. };
  64541. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64542. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64543. if (invertY === void 0) { invertY = false; }
  64544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64545. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64546. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64547. };
  64548. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64549. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64550. if (invertY === void 0) { invertY = false; }
  64551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64552. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64553. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64554. };
  64555. return RawTexture;
  64556. }(BABYLON.Texture));
  64557. BABYLON.RawTexture = RawTexture;
  64558. })(BABYLON || (BABYLON = {}));
  64559. //# sourceMappingURL=babylon.rawTexture.js.map
  64560. var BABYLON;
  64561. (function (BABYLON) {
  64562. /**
  64563. * Class used to store 3D textures containing user data
  64564. */
  64565. var RawTexture3D = /** @class */ (function (_super) {
  64566. __extends(RawTexture3D, _super);
  64567. /**
  64568. * Create a new RawTexture3D
  64569. * @param data defines the data of the texture
  64570. * @param width defines the width of the texture
  64571. * @param height defines the height of the texture
  64572. * @param depth defines the depth of the texture
  64573. * @param format defines the texture format to use
  64574. * @param scene defines the hosting scene
  64575. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64576. * @param invertY defines if texture must be stored with Y axis inverted
  64577. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64578. */
  64579. function RawTexture3D(data, width, height, depth,
  64580. /** Gets or sets the texture format to use*/
  64581. format, scene, generateMipMaps, invertY, samplingMode) {
  64582. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64583. if (invertY === void 0) { invertY = false; }
  64584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64585. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64586. _this.format = format;
  64587. _this._engine = scene.getEngine();
  64588. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64589. _this.is3D = true;
  64590. return _this;
  64591. }
  64592. /**
  64593. * Update the texture with new data
  64594. * @param data defines the data to store in the texture
  64595. */
  64596. RawTexture3D.prototype.update = function (data) {
  64597. if (!this._texture) {
  64598. return;
  64599. }
  64600. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64601. };
  64602. return RawTexture3D;
  64603. }(BABYLON.Texture));
  64604. BABYLON.RawTexture3D = RawTexture3D;
  64605. })(BABYLON || (BABYLON = {}));
  64606. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64607. var BABYLON;
  64608. (function (BABYLON) {
  64609. /**
  64610. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64611. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64612. */
  64613. var PostProcess = /** @class */ (function () {
  64614. /**
  64615. * Creates a new instance PostProcess
  64616. * @param name The name of the PostProcess.
  64617. * @param fragmentUrl The url of the fragment shader to be used.
  64618. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64619. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64620. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64621. * @param camera The camera to apply the render pass to.
  64622. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64623. * @param engine The engine which the post process will be applied. (default: current engine)
  64624. * @param reusable If the post process can be reused on the same frame. (default: false)
  64625. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64626. * @param textureType Type of textures used when performing the post process. (default: 0)
  64627. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64628. * @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
  64629. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64630. */
  64631. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64633. if (defines === void 0) { defines = null; }
  64634. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64635. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64636. if (blockCompilation === void 0) { blockCompilation = false; }
  64637. this.name = name;
  64638. /**
  64639. * Width of the texture to apply the post process on
  64640. */
  64641. this.width = -1;
  64642. /**
  64643. * Height of the texture to apply the post process on
  64644. */
  64645. this.height = -1;
  64646. /**
  64647. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64648. */
  64649. this._outputTexture = null;
  64650. /**
  64651. * If the buffer needs to be cleared before applying the post process. (default: true)
  64652. * Should be set to false if shader will overwrite all previous pixels.
  64653. */
  64654. this.autoClear = true;
  64655. /**
  64656. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64657. */
  64658. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64659. /**
  64660. * Animations to be used for the post processing
  64661. */
  64662. this.animations = new Array();
  64663. /**
  64664. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64665. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64666. */
  64667. this.enablePixelPerfectMode = false;
  64668. /**
  64669. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64670. */
  64671. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64672. /**
  64673. * Force textures to be a power of two (default: false)
  64674. */
  64675. this.alwaysForcePOT = false;
  64676. /**
  64677. * Number of sample textures (default: 1)
  64678. */
  64679. this.samples = 1;
  64680. /**
  64681. * Modify the scale of the post process to be the same as the viewport (default: false)
  64682. */
  64683. this.adaptScaleToCurrentViewport = false;
  64684. this._reusable = false;
  64685. /**
  64686. * Smart array of input and output textures for the post process.
  64687. */
  64688. this._textures = new BABYLON.SmartArray(2);
  64689. /**
  64690. * The index in _textures that corresponds to the output texture.
  64691. */
  64692. this._currentRenderTextureInd = 0;
  64693. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64694. this._texelSize = BABYLON.Vector2.Zero();
  64695. // Events
  64696. /**
  64697. * An event triggered when the postprocess is activated.
  64698. */
  64699. this.onActivateObservable = new BABYLON.Observable();
  64700. /**
  64701. * An event triggered when the postprocess changes its size.
  64702. */
  64703. this.onSizeChangedObservable = new BABYLON.Observable();
  64704. /**
  64705. * An event triggered when the postprocess applies its effect.
  64706. */
  64707. this.onApplyObservable = new BABYLON.Observable();
  64708. /**
  64709. * An event triggered before rendering the postprocess
  64710. */
  64711. this.onBeforeRenderObservable = new BABYLON.Observable();
  64712. /**
  64713. * An event triggered after rendering the postprocess
  64714. */
  64715. this.onAfterRenderObservable = new BABYLON.Observable();
  64716. if (camera != null) {
  64717. this._camera = camera;
  64718. this._scene = camera.getScene();
  64719. camera.attachPostProcess(this);
  64720. this._engine = this._scene.getEngine();
  64721. this._scene.postProcesses.push(this);
  64722. }
  64723. else if (engine) {
  64724. this._engine = engine;
  64725. this._engine.postProcesses.push(this);
  64726. }
  64727. this._options = options;
  64728. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64729. this._reusable = reusable || false;
  64730. this._textureType = textureType;
  64731. this._samplers = samplers || [];
  64732. this._samplers.push("textureSampler");
  64733. this._fragmentUrl = fragmentUrl;
  64734. this._vertexUrl = vertexUrl;
  64735. this._parameters = parameters || [];
  64736. this._parameters.push("scale");
  64737. this._indexParameters = indexParameters;
  64738. if (!blockCompilation) {
  64739. this.updateEffect(defines);
  64740. }
  64741. }
  64742. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64743. /**
  64744. * A function that is added to the onActivateObservable
  64745. */
  64746. set: function (callback) {
  64747. if (this._onActivateObserver) {
  64748. this.onActivateObservable.remove(this._onActivateObserver);
  64749. }
  64750. if (callback) {
  64751. this._onActivateObserver = this.onActivateObservable.add(callback);
  64752. }
  64753. },
  64754. enumerable: true,
  64755. configurable: true
  64756. });
  64757. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64758. /**
  64759. * A function that is added to the onSizeChangedObservable
  64760. */
  64761. set: function (callback) {
  64762. if (this._onSizeChangedObserver) {
  64763. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64764. }
  64765. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64766. },
  64767. enumerable: true,
  64768. configurable: true
  64769. });
  64770. Object.defineProperty(PostProcess.prototype, "onApply", {
  64771. /**
  64772. * A function that is added to the onApplyObservable
  64773. */
  64774. set: function (callback) {
  64775. if (this._onApplyObserver) {
  64776. this.onApplyObservable.remove(this._onApplyObserver);
  64777. }
  64778. this._onApplyObserver = this.onApplyObservable.add(callback);
  64779. },
  64780. enumerable: true,
  64781. configurable: true
  64782. });
  64783. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64784. /**
  64785. * A function that is added to the onBeforeRenderObservable
  64786. */
  64787. set: function (callback) {
  64788. if (this._onBeforeRenderObserver) {
  64789. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64790. }
  64791. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64792. },
  64793. enumerable: true,
  64794. configurable: true
  64795. });
  64796. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64797. /**
  64798. * A function that is added to the onAfterRenderObservable
  64799. */
  64800. set: function (callback) {
  64801. if (this._onAfterRenderObserver) {
  64802. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64803. }
  64804. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64805. },
  64806. enumerable: true,
  64807. configurable: true
  64808. });
  64809. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64810. /**
  64811. * 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
  64812. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64813. */
  64814. get: function () {
  64815. return this._textures.data[this._currentRenderTextureInd];
  64816. },
  64817. set: function (value) {
  64818. this._forcedOutputTexture = value;
  64819. },
  64820. enumerable: true,
  64821. configurable: true
  64822. });
  64823. /**
  64824. * Gets the camera which post process is applied to.
  64825. * @returns The camera the post process is applied to.
  64826. */
  64827. PostProcess.prototype.getCamera = function () {
  64828. return this._camera;
  64829. };
  64830. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64831. /**
  64832. * Gets the texel size of the postprocess.
  64833. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64834. */
  64835. get: function () {
  64836. if (this._shareOutputWithPostProcess) {
  64837. return this._shareOutputWithPostProcess.texelSize;
  64838. }
  64839. if (this._forcedOutputTexture) {
  64840. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64841. }
  64842. return this._texelSize;
  64843. },
  64844. enumerable: true,
  64845. configurable: true
  64846. });
  64847. /**
  64848. * Gets the engine which this post process belongs to.
  64849. * @returns The engine the post process was enabled with.
  64850. */
  64851. PostProcess.prototype.getEngine = function () {
  64852. return this._engine;
  64853. };
  64854. /**
  64855. * The effect that is created when initializing the post process.
  64856. * @returns The created effect corrisponding the the postprocess.
  64857. */
  64858. PostProcess.prototype.getEffect = function () {
  64859. return this._effect;
  64860. };
  64861. /**
  64862. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64863. * @param postProcess The post process to share the output with.
  64864. * @returns This post process.
  64865. */
  64866. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64867. this._disposeTextures();
  64868. this._shareOutputWithPostProcess = postProcess;
  64869. return this;
  64870. };
  64871. /**
  64872. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64873. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64874. */
  64875. PostProcess.prototype.useOwnOutput = function () {
  64876. if (this._textures.length == 0) {
  64877. this._textures = new BABYLON.SmartArray(2);
  64878. }
  64879. this._shareOutputWithPostProcess = null;
  64880. };
  64881. /**
  64882. * Updates the effect with the current post process compile time values and recompiles the shader.
  64883. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64884. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64885. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64886. * @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
  64887. * @param onCompiled Called when the shader has been compiled.
  64888. * @param onError Called if there is an error when compiling a shader.
  64889. */
  64890. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64891. if (defines === void 0) { defines = null; }
  64892. if (uniforms === void 0) { uniforms = null; }
  64893. if (samplers === void 0) { samplers = null; }
  64894. 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);
  64895. };
  64896. /**
  64897. * The post process is reusable if it can be used multiple times within one frame.
  64898. * @returns If the post process is reusable
  64899. */
  64900. PostProcess.prototype.isReusable = function () {
  64901. return this._reusable;
  64902. };
  64903. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64904. PostProcess.prototype.markTextureDirty = function () {
  64905. this.width = -1;
  64906. };
  64907. /**
  64908. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64909. * 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.
  64910. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64911. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64912. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64913. * @returns The target texture that was bound to be written to.
  64914. */
  64915. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64916. var _this = this;
  64917. if (sourceTexture === void 0) { sourceTexture = null; }
  64918. camera = camera || this._camera;
  64919. var scene = camera.getScene();
  64920. var engine = scene.getEngine();
  64921. var maxSize = engine.getCaps().maxTextureSize;
  64922. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64923. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64924. // 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
  64925. var webVRCamera = camera.parent;
  64926. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64927. requiredWidth /= 2;
  64928. }
  64929. var desiredWidth = (this._options.width || requiredWidth);
  64930. var desiredHeight = this._options.height || requiredHeight;
  64931. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64932. if (this.adaptScaleToCurrentViewport) {
  64933. var currentViewport = engine.currentViewport;
  64934. if (currentViewport) {
  64935. desiredWidth *= currentViewport.width;
  64936. desiredHeight *= currentViewport.height;
  64937. }
  64938. }
  64939. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64940. if (!this._options.width) {
  64941. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64942. }
  64943. if (!this._options.height) {
  64944. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64945. }
  64946. }
  64947. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64948. if (this._textures.length > 0) {
  64949. for (var i = 0; i < this._textures.length; i++) {
  64950. this._engine._releaseTexture(this._textures.data[i]);
  64951. }
  64952. this._textures.reset();
  64953. }
  64954. this.width = desiredWidth;
  64955. this.height = desiredHeight;
  64956. var textureSize = { width: this.width, height: this.height };
  64957. var textureOptions = {
  64958. generateMipMaps: false,
  64959. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64960. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64961. samplingMode: this.renderTargetSamplingMode,
  64962. type: this._textureType
  64963. };
  64964. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64965. if (this._reusable) {
  64966. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64967. }
  64968. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64969. this.onSizeChangedObservable.notifyObservers(this);
  64970. }
  64971. this._textures.forEach(function (texture) {
  64972. if (texture.samples !== _this.samples) {
  64973. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64974. }
  64975. });
  64976. }
  64977. var target;
  64978. if (this._shareOutputWithPostProcess) {
  64979. target = this._shareOutputWithPostProcess.inputTexture;
  64980. }
  64981. else if (this._forcedOutputTexture) {
  64982. target = this._forcedOutputTexture;
  64983. this.width = this._forcedOutputTexture.width;
  64984. this.height = this._forcedOutputTexture.height;
  64985. }
  64986. else {
  64987. target = this.inputTexture;
  64988. }
  64989. // Bind the input of this post process to be used as the output of the previous post process.
  64990. if (this.enablePixelPerfectMode) {
  64991. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64992. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64993. }
  64994. else {
  64995. this._scaleRatio.copyFromFloats(1, 1);
  64996. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64997. }
  64998. this.onActivateObservable.notifyObservers(camera);
  64999. // Clear
  65000. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65001. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65002. }
  65003. if (this._reusable) {
  65004. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65005. }
  65006. return target;
  65007. };
  65008. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65009. /**
  65010. * If the post process is supported.
  65011. */
  65012. get: function () {
  65013. return this._effect.isSupported;
  65014. },
  65015. enumerable: true,
  65016. configurable: true
  65017. });
  65018. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65019. /**
  65020. * The aspect ratio of the output texture.
  65021. */
  65022. get: function () {
  65023. if (this._shareOutputWithPostProcess) {
  65024. return this._shareOutputWithPostProcess.aspectRatio;
  65025. }
  65026. if (this._forcedOutputTexture) {
  65027. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65028. }
  65029. return this.width / this.height;
  65030. },
  65031. enumerable: true,
  65032. configurable: true
  65033. });
  65034. /**
  65035. * Get a value indicating if the post-process is ready to be used
  65036. * @returns true if the post-process is ready (shader is compiled)
  65037. */
  65038. PostProcess.prototype.isReady = function () {
  65039. return this._effect && this._effect.isReady();
  65040. };
  65041. /**
  65042. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65043. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65044. */
  65045. PostProcess.prototype.apply = function () {
  65046. // Check
  65047. if (!this._effect || !this._effect.isReady())
  65048. return null;
  65049. // States
  65050. this._engine.enableEffect(this._effect);
  65051. this._engine.setState(false);
  65052. this._engine.setDepthBuffer(false);
  65053. this._engine.setDepthWrite(false);
  65054. // Alpha
  65055. this._engine.setAlphaMode(this.alphaMode);
  65056. if (this.alphaConstants) {
  65057. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65058. }
  65059. // Bind the output texture of the preivous post process as the input to this post process.
  65060. var source;
  65061. if (this._shareOutputWithPostProcess) {
  65062. source = this._shareOutputWithPostProcess.inputTexture;
  65063. }
  65064. else if (this._forcedOutputTexture) {
  65065. source = this._forcedOutputTexture;
  65066. }
  65067. else {
  65068. source = this.inputTexture;
  65069. }
  65070. this._effect._bindTexture("textureSampler", source);
  65071. // Parameters
  65072. this._effect.setVector2("scale", this._scaleRatio);
  65073. this.onApplyObservable.notifyObservers(this._effect);
  65074. return this._effect;
  65075. };
  65076. PostProcess.prototype._disposeTextures = function () {
  65077. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65078. return;
  65079. }
  65080. if (this._textures.length > 0) {
  65081. for (var i = 0; i < this._textures.length; i++) {
  65082. this._engine._releaseTexture(this._textures.data[i]);
  65083. }
  65084. }
  65085. this._textures.dispose();
  65086. };
  65087. /**
  65088. * Disposes the post process.
  65089. * @param camera The camera to dispose the post process on.
  65090. */
  65091. PostProcess.prototype.dispose = function (camera) {
  65092. camera = camera || this._camera;
  65093. this._disposeTextures();
  65094. if (this._scene) {
  65095. var index_1 = this._scene.postProcesses.indexOf(this);
  65096. if (index_1 !== -1) {
  65097. this._scene.postProcesses.splice(index_1, 1);
  65098. }
  65099. }
  65100. else {
  65101. var index_2 = this._engine.postProcesses.indexOf(this);
  65102. if (index_2 !== -1) {
  65103. this._engine.postProcesses.splice(index_2, 1);
  65104. }
  65105. }
  65106. if (!camera) {
  65107. return;
  65108. }
  65109. camera.detachPostProcess(this);
  65110. var index = camera._postProcesses.indexOf(this);
  65111. if (index === 0 && camera._postProcesses.length > 0) {
  65112. var firstPostProcess = this._camera._getFirstPostProcess();
  65113. if (firstPostProcess) {
  65114. firstPostProcess.markTextureDirty();
  65115. }
  65116. }
  65117. this.onActivateObservable.clear();
  65118. this.onAfterRenderObservable.clear();
  65119. this.onApplyObservable.clear();
  65120. this.onBeforeRenderObservable.clear();
  65121. this.onSizeChangedObservable.clear();
  65122. };
  65123. return PostProcess;
  65124. }());
  65125. BABYLON.PostProcess = PostProcess;
  65126. })(BABYLON || (BABYLON = {}));
  65127. //# sourceMappingURL=babylon.postProcess.js.map
  65128. var BABYLON;
  65129. (function (BABYLON) {
  65130. var PassPostProcess = /** @class */ (function (_super) {
  65131. __extends(PassPostProcess, _super);
  65132. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65133. if (camera === void 0) { camera = null; }
  65134. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65135. if (blockCompilation === void 0) { blockCompilation = false; }
  65136. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65137. }
  65138. return PassPostProcess;
  65139. }(BABYLON.PostProcess));
  65140. BABYLON.PassPostProcess = PassPostProcess;
  65141. })(BABYLON || (BABYLON = {}));
  65142. //# sourceMappingURL=babylon.passPostProcess.js.map
  65143. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65144. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65145. s = arguments[i];
  65146. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65147. t[p] = s[p];
  65148. }
  65149. return t;
  65150. };
  65151. var BABYLON;
  65152. (function (BABYLON) {
  65153. /**
  65154. * Default implementation IShadowGenerator.
  65155. * This is the main object responsible of generating shadows in the framework.
  65156. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65157. */
  65158. var ShadowGenerator = /** @class */ (function () {
  65159. /**
  65160. * Creates a ShadowGenerator object.
  65161. * A ShadowGenerator is the required tool to use the shadows.
  65162. * Each light casting shadows needs to use its own ShadowGenerator.
  65163. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65164. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65165. * @param light The light object generating the shadows.
  65166. * @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.
  65167. */
  65168. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65169. this._bias = 0.00005;
  65170. this._normalBias = 0;
  65171. this._blurBoxOffset = 1;
  65172. this._blurScale = 2;
  65173. this._blurKernel = 1;
  65174. this._useKernelBlur = false;
  65175. this._filter = ShadowGenerator.FILTER_NONE;
  65176. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65177. this._contactHardeningLightSizeUVRatio = 0.1;
  65178. this._darkness = 0;
  65179. this._transparencyShadow = false;
  65180. /**
  65181. * Controls the extent to which the shadows fade out at the edge of the frustum
  65182. * Used only by directionals and spots
  65183. */
  65184. this.frustumEdgeFalloff = 0;
  65185. /**
  65186. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65187. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65188. * It might on the other hand introduce peter panning.
  65189. */
  65190. this.forceBackFacesOnly = false;
  65191. this._lightDirection = BABYLON.Vector3.Zero();
  65192. this._viewMatrix = BABYLON.Matrix.Zero();
  65193. this._projectionMatrix = BABYLON.Matrix.Zero();
  65194. this._transformMatrix = BABYLON.Matrix.Zero();
  65195. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65196. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65197. this._currentFaceIndex = 0;
  65198. this._currentFaceIndexCache = 0;
  65199. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65200. this._mapSize = mapSize;
  65201. this._light = light;
  65202. this._scene = light.getScene();
  65203. light._shadowGenerator = this;
  65204. // Texture type fallback from float to int if not supported.
  65205. var caps = this._scene.getEngine().getCaps();
  65206. if (!useFullFloatFirst) {
  65207. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65208. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65209. }
  65210. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65211. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65212. }
  65213. else {
  65214. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65215. }
  65216. }
  65217. else {
  65218. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65219. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65220. }
  65221. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65222. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65223. }
  65224. else {
  65225. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65226. }
  65227. }
  65228. this._initializeGenerator();
  65229. this._applyFilterValues();
  65230. }
  65231. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65232. /**
  65233. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65234. */
  65235. get: function () {
  65236. return this._bias;
  65237. },
  65238. /**
  65239. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65240. */
  65241. set: function (bias) {
  65242. this._bias = bias;
  65243. },
  65244. enumerable: true,
  65245. configurable: true
  65246. });
  65247. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65248. /**
  65249. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65250. */
  65251. get: function () {
  65252. return this._normalBias;
  65253. },
  65254. /**
  65255. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65256. */
  65257. set: function (normalBias) {
  65258. this._normalBias = normalBias;
  65259. },
  65260. enumerable: true,
  65261. configurable: true
  65262. });
  65263. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65264. /**
  65265. * Gets the blur box offset: offset applied during the blur pass.
  65266. * Only usefull if useKernelBlur = false
  65267. */
  65268. get: function () {
  65269. return this._blurBoxOffset;
  65270. },
  65271. /**
  65272. * Sets the blur box offset: offset applied during the blur pass.
  65273. * Only usefull if useKernelBlur = false
  65274. */
  65275. set: function (value) {
  65276. if (this._blurBoxOffset === value) {
  65277. return;
  65278. }
  65279. this._blurBoxOffset = value;
  65280. this._disposeBlurPostProcesses();
  65281. },
  65282. enumerable: true,
  65283. configurable: true
  65284. });
  65285. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65286. /**
  65287. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65288. * 2 means half of the size.
  65289. */
  65290. get: function () {
  65291. return this._blurScale;
  65292. },
  65293. /**
  65294. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65295. * 2 means half of the size.
  65296. */
  65297. set: function (value) {
  65298. if (this._blurScale === value) {
  65299. return;
  65300. }
  65301. this._blurScale = value;
  65302. this._disposeBlurPostProcesses();
  65303. },
  65304. enumerable: true,
  65305. configurable: true
  65306. });
  65307. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65308. /**
  65309. * Gets the blur kernel: kernel size of the blur pass.
  65310. * Only usefull if useKernelBlur = true
  65311. */
  65312. get: function () {
  65313. return this._blurKernel;
  65314. },
  65315. /**
  65316. * Sets the blur kernel: kernel size of the blur pass.
  65317. * Only usefull if useKernelBlur = true
  65318. */
  65319. set: function (value) {
  65320. if (this._blurKernel === value) {
  65321. return;
  65322. }
  65323. this._blurKernel = value;
  65324. this._disposeBlurPostProcesses();
  65325. },
  65326. enumerable: true,
  65327. configurable: true
  65328. });
  65329. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65330. /**
  65331. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65332. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65333. */
  65334. get: function () {
  65335. return this._useKernelBlur;
  65336. },
  65337. /**
  65338. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65339. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65340. */
  65341. set: function (value) {
  65342. if (this._useKernelBlur === value) {
  65343. return;
  65344. }
  65345. this._useKernelBlur = value;
  65346. this._disposeBlurPostProcesses();
  65347. },
  65348. enumerable: true,
  65349. configurable: true
  65350. });
  65351. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65352. /**
  65353. * Gets the depth scale used in ESM mode.
  65354. */
  65355. get: function () {
  65356. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65357. },
  65358. /**
  65359. * Sets the depth scale used in ESM mode.
  65360. * This can override the scale stored on the light.
  65361. */
  65362. set: function (value) {
  65363. this._depthScale = value;
  65364. },
  65365. enumerable: true,
  65366. configurable: true
  65367. });
  65368. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65369. /**
  65370. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65371. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65372. */
  65373. get: function () {
  65374. return this._filter;
  65375. },
  65376. /**
  65377. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65378. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65379. */
  65380. set: function (value) {
  65381. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65382. if (this._light.needCube()) {
  65383. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65384. this.useExponentialShadowMap = true;
  65385. return;
  65386. }
  65387. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65388. this.useCloseExponentialShadowMap = true;
  65389. return;
  65390. }
  65391. // PCF on cubemap would also be expensive
  65392. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65393. this.usePoissonSampling = true;
  65394. return;
  65395. }
  65396. }
  65397. // Weblg1 fallback for PCF.
  65398. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65399. if (this._scene.getEngine().webGLVersion === 1) {
  65400. this.usePoissonSampling = true;
  65401. return;
  65402. }
  65403. }
  65404. if (this._filter === value) {
  65405. return;
  65406. }
  65407. this._filter = value;
  65408. this._disposeBlurPostProcesses();
  65409. this._applyFilterValues();
  65410. this._light._markMeshesAsLightDirty();
  65411. },
  65412. enumerable: true,
  65413. configurable: true
  65414. });
  65415. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65416. /**
  65417. * Gets if the current filter is set to Poisson Sampling.
  65418. */
  65419. get: function () {
  65420. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65421. },
  65422. /**
  65423. * Sets the current filter to Poisson Sampling.
  65424. */
  65425. set: function (value) {
  65426. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65427. return;
  65428. }
  65429. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65430. },
  65431. enumerable: true,
  65432. configurable: true
  65433. });
  65434. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65435. /**
  65436. * Gets if the current filter is set to VSM.
  65437. * DEPRECATED. Should use useExponentialShadowMap instead.
  65438. */
  65439. get: function () {
  65440. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65441. return this.useExponentialShadowMap;
  65442. },
  65443. /**
  65444. * Sets the current filter is to VSM.
  65445. * DEPRECATED. Should use useExponentialShadowMap instead.
  65446. */
  65447. set: function (value) {
  65448. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65449. this.useExponentialShadowMap = value;
  65450. },
  65451. enumerable: true,
  65452. configurable: true
  65453. });
  65454. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65455. /**
  65456. * Gets if the current filter is set to blurred VSM.
  65457. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65458. */
  65459. get: function () {
  65460. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65461. return this.useBlurExponentialShadowMap;
  65462. },
  65463. /**
  65464. * Sets the current filter is to blurred VSM.
  65465. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65466. */
  65467. set: function (value) {
  65468. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65469. this.useBlurExponentialShadowMap = value;
  65470. },
  65471. enumerable: true,
  65472. configurable: true
  65473. });
  65474. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65475. /**
  65476. * Gets if the current filter is set to ESM.
  65477. */
  65478. get: function () {
  65479. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65480. },
  65481. /**
  65482. * Sets the current filter is to ESM.
  65483. */
  65484. set: function (value) {
  65485. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65486. return;
  65487. }
  65488. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65489. },
  65490. enumerable: true,
  65491. configurable: true
  65492. });
  65493. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65494. /**
  65495. * Gets if the current filter is set to filtered ESM.
  65496. */
  65497. get: function () {
  65498. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65499. },
  65500. /**
  65501. * Gets if the current filter is set to filtered ESM.
  65502. */
  65503. set: function (value) {
  65504. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65505. return;
  65506. }
  65507. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65508. },
  65509. enumerable: true,
  65510. configurable: true
  65511. });
  65512. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65513. /**
  65514. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65515. * exponential to prevent steep falloff artifacts).
  65516. */
  65517. get: function () {
  65518. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65519. },
  65520. /**
  65521. * Sets the current filter to "close ESM" (using the inverse of the
  65522. * exponential to prevent steep falloff artifacts).
  65523. */
  65524. set: function (value) {
  65525. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65526. return;
  65527. }
  65528. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65529. },
  65530. enumerable: true,
  65531. configurable: true
  65532. });
  65533. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65534. /**
  65535. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65536. * exponential to prevent steep falloff artifacts).
  65537. */
  65538. get: function () {
  65539. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65540. },
  65541. /**
  65542. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65543. * exponential to prevent steep falloff artifacts).
  65544. */
  65545. set: function (value) {
  65546. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65547. return;
  65548. }
  65549. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65550. },
  65551. enumerable: true,
  65552. configurable: true
  65553. });
  65554. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65555. /**
  65556. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65557. */
  65558. get: function () {
  65559. return this.filter === ShadowGenerator.FILTER_PCF;
  65560. },
  65561. /**
  65562. * Sets the current filter to "PCF" (percentage closer filtering).
  65563. */
  65564. set: function (value) {
  65565. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65566. return;
  65567. }
  65568. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65574. /**
  65575. * Gets the PCF or PCSS Quality.
  65576. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65577. */
  65578. get: function () {
  65579. return this._filteringQuality;
  65580. },
  65581. /**
  65582. * Sets the PCF or PCSS Quality.
  65583. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65584. */
  65585. set: function (filteringQuality) {
  65586. this._filteringQuality = filteringQuality;
  65587. },
  65588. enumerable: true,
  65589. configurable: true
  65590. });
  65591. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65592. /**
  65593. * Gets if the current filter is set to "PCSS" (contact hardening).
  65594. */
  65595. get: function () {
  65596. return this.filter === ShadowGenerator.FILTER_PCSS;
  65597. },
  65598. /**
  65599. * Sets the current filter to "PCSS" (contact hardening).
  65600. */
  65601. set: function (value) {
  65602. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65603. return;
  65604. }
  65605. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65606. },
  65607. enumerable: true,
  65608. configurable: true
  65609. });
  65610. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65611. /**
  65612. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65613. * Using a ratio helps keeping shape stability independently of the map size.
  65614. *
  65615. * It does not account for the light projection as it was having too much
  65616. * instability during the light setup or during light position changes.
  65617. *
  65618. * Only valid if useContactHardeningShadow is true.
  65619. */
  65620. get: function () {
  65621. return this._contactHardeningLightSizeUVRatio;
  65622. },
  65623. /**
  65624. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65625. * Using a ratio helps keeping shape stability independently of the map size.
  65626. *
  65627. * It does not account for the light projection as it was having too much
  65628. * instability during the light setup or during light position changes.
  65629. *
  65630. * Only valid if useContactHardeningShadow is true.
  65631. */
  65632. set: function (contactHardeningLightSizeUVRatio) {
  65633. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65634. },
  65635. enumerable: true,
  65636. configurable: true
  65637. });
  65638. /**
  65639. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65640. * 0 means strongest and 1 would means no shadow.
  65641. * @returns the darkness.
  65642. */
  65643. ShadowGenerator.prototype.getDarkness = function () {
  65644. return this._darkness;
  65645. };
  65646. /**
  65647. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65648. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65649. * @returns the shadow generator allowing fluent coding.
  65650. */
  65651. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65652. if (darkness >= 1.0)
  65653. this._darkness = 1.0;
  65654. else if (darkness <= 0.0)
  65655. this._darkness = 0.0;
  65656. else
  65657. this._darkness = darkness;
  65658. return this;
  65659. };
  65660. /**
  65661. * Sets the ability to have transparent shadow (boolean).
  65662. * @param transparent True if transparent else False
  65663. * @returns the shadow generator allowing fluent coding
  65664. */
  65665. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65666. this._transparencyShadow = transparent;
  65667. return this;
  65668. };
  65669. /**
  65670. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65671. * @returns The render target texture if present otherwise, null
  65672. */
  65673. ShadowGenerator.prototype.getShadowMap = function () {
  65674. return this._shadowMap;
  65675. };
  65676. /**
  65677. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65678. * @returns The render target texture if the shadow map is present otherwise, null
  65679. */
  65680. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65681. if (this._shadowMap2) {
  65682. return this._shadowMap2;
  65683. }
  65684. return this._shadowMap;
  65685. };
  65686. /**
  65687. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65688. * @param mesh Mesh to add
  65689. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65690. * @returns the Shadow Generator itself
  65691. */
  65692. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65693. if (includeDescendants === void 0) { includeDescendants = true; }
  65694. if (!this._shadowMap) {
  65695. return this;
  65696. }
  65697. if (!this._shadowMap.renderList) {
  65698. this._shadowMap.renderList = [];
  65699. }
  65700. this._shadowMap.renderList.push(mesh);
  65701. if (includeDescendants) {
  65702. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65703. }
  65704. return this;
  65705. var _a;
  65706. };
  65707. /**
  65708. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65709. * @param mesh Mesh to remove
  65710. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65711. * @returns the Shadow Generator itself
  65712. */
  65713. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65714. if (includeDescendants === void 0) { includeDescendants = true; }
  65715. if (!this._shadowMap || !this._shadowMap.renderList) {
  65716. return this;
  65717. }
  65718. var index = this._shadowMap.renderList.indexOf(mesh);
  65719. if (index !== -1) {
  65720. this._shadowMap.renderList.splice(index, 1);
  65721. }
  65722. if (includeDescendants) {
  65723. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65724. var child = _a[_i];
  65725. this.removeShadowCaster(child);
  65726. }
  65727. }
  65728. return this;
  65729. };
  65730. /**
  65731. * Returns the associated light object.
  65732. * @returns the light generating the shadow
  65733. */
  65734. ShadowGenerator.prototype.getLight = function () {
  65735. return this._light;
  65736. };
  65737. ShadowGenerator.prototype._initializeGenerator = function () {
  65738. this._light._markMeshesAsLightDirty();
  65739. this._initializeShadowMap();
  65740. };
  65741. ShadowGenerator.prototype._initializeShadowMap = function () {
  65742. var _this = this;
  65743. // Render target
  65744. var engine = this._scene.getEngine();
  65745. if (engine.webGLVersion > 1) {
  65746. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65747. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65748. }
  65749. else {
  65750. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65751. }
  65752. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65753. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65754. this._shadowMap.anisotropicFilteringLevel = 1;
  65755. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65756. this._shadowMap.renderParticles = false;
  65757. this._shadowMap.ignoreCameraViewport = true;
  65758. // Record Face Index before render.
  65759. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65760. _this._currentFaceIndex = faceIndex;
  65761. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65762. engine.setColorWrite(false);
  65763. }
  65764. });
  65765. // Custom render function.
  65766. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65767. // Blur if required afer render.
  65768. this._shadowMap.onAfterUnbindObservable.add(function () {
  65769. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65770. engine.setColorWrite(true);
  65771. }
  65772. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65773. return;
  65774. }
  65775. var shadowMap = _this.getShadowMapForRendering();
  65776. if (shadowMap) {
  65777. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65778. }
  65779. });
  65780. // Clear according to the chosen filter.
  65781. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65782. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65783. this._shadowMap.onClearObservable.add(function (engine) {
  65784. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65785. engine.clear(clearOne, false, true, false);
  65786. }
  65787. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65788. engine.clear(clearZero, true, true, false);
  65789. }
  65790. else {
  65791. engine.clear(clearOne, true, true, false);
  65792. }
  65793. });
  65794. };
  65795. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65796. var _this = this;
  65797. var engine = this._scene.getEngine();
  65798. var targetSize = this._mapSize / this.blurScale;
  65799. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65800. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65801. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65802. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65803. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65804. }
  65805. if (this.useKernelBlur) {
  65806. 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);
  65807. this._kernelBlurXPostprocess.width = targetSize;
  65808. this._kernelBlurXPostprocess.height = targetSize;
  65809. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65810. effect.setTexture("textureSampler", _this._shadowMap);
  65811. });
  65812. 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);
  65813. this._kernelBlurXPostprocess.autoClear = false;
  65814. this._kernelBlurYPostprocess.autoClear = false;
  65815. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65816. this._kernelBlurXPostprocess.packedFloat = true;
  65817. this._kernelBlurYPostprocess.packedFloat = true;
  65818. }
  65819. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65820. }
  65821. else {
  65822. 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);
  65823. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65824. effect.setFloat2("screenSize", targetSize, targetSize);
  65825. effect.setTexture("textureSampler", _this._shadowMap);
  65826. });
  65827. this._boxBlurPostprocess.autoClear = false;
  65828. this._blurPostProcesses = [this._boxBlurPostprocess];
  65829. }
  65830. };
  65831. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65832. var index;
  65833. var engine = this._scene.getEngine();
  65834. if (depthOnlySubMeshes.length) {
  65835. engine.setColorWrite(false);
  65836. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65837. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65838. }
  65839. engine.setColorWrite(true);
  65840. }
  65841. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65842. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65843. }
  65844. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65845. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65846. }
  65847. if (this._transparencyShadow) {
  65848. for (index = 0; index < transparentSubMeshes.length; index++) {
  65849. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65850. }
  65851. }
  65852. };
  65853. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65854. var _this = this;
  65855. var mesh = subMesh.getRenderingMesh();
  65856. var scene = this._scene;
  65857. var engine = scene.getEngine();
  65858. var material = subMesh.getMaterial();
  65859. if (!material) {
  65860. return;
  65861. }
  65862. // Culling
  65863. engine.setState(material.backFaceCulling);
  65864. // Managing instances
  65865. var batch = mesh._getInstancesRenderList(subMesh._id);
  65866. if (batch.mustReturn) {
  65867. return;
  65868. }
  65869. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65870. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65871. engine.enableEffect(this._effect);
  65872. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65873. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65874. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65875. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65876. this._effect.setVector3("lightData", this._cachedDirection);
  65877. }
  65878. else {
  65879. this._effect.setVector3("lightData", this._cachedPosition);
  65880. }
  65881. if (scene.activeCamera) {
  65882. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65883. }
  65884. // Alpha test
  65885. if (material && material.needAlphaTesting()) {
  65886. var alphaTexture = material.getAlphaTestTexture();
  65887. if (alphaTexture) {
  65888. this._effect.setTexture("diffuseSampler", alphaTexture);
  65889. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65890. }
  65891. }
  65892. // Bones
  65893. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65894. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65895. }
  65896. // Morph targets
  65897. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65898. if (this.forceBackFacesOnly) {
  65899. engine.setState(true, 0, false, true);
  65900. }
  65901. // Draw
  65902. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65903. if (this.forceBackFacesOnly) {
  65904. engine.setState(true, 0, false, false);
  65905. }
  65906. }
  65907. else {
  65908. // Need to reset refresh rate of the shadowMap
  65909. if (this._shadowMap) {
  65910. this._shadowMap.resetRefreshCounter();
  65911. }
  65912. }
  65913. };
  65914. ShadowGenerator.prototype._applyFilterValues = function () {
  65915. if (!this._shadowMap) {
  65916. return;
  65917. }
  65918. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65919. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65920. }
  65921. else {
  65922. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65923. }
  65924. };
  65925. /**
  65926. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65927. * @param onCompiled Callback triggered at the and of the effects compilation
  65928. * @param options Sets of optional options forcing the compilation with different modes
  65929. */
  65930. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65931. var _this = this;
  65932. var localOptions = __assign({ useInstances: false }, options);
  65933. var shadowMap = this.getShadowMap();
  65934. if (!shadowMap) {
  65935. if (onCompiled) {
  65936. onCompiled(this);
  65937. }
  65938. return;
  65939. }
  65940. var renderList = shadowMap.renderList;
  65941. if (!renderList) {
  65942. if (onCompiled) {
  65943. onCompiled(this);
  65944. }
  65945. return;
  65946. }
  65947. var subMeshes = new Array();
  65948. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65949. var mesh = renderList_1[_i];
  65950. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65951. }
  65952. if (subMeshes.length === 0) {
  65953. if (onCompiled) {
  65954. onCompiled(this);
  65955. }
  65956. return;
  65957. }
  65958. var currentIndex = 0;
  65959. var checkReady = function () {
  65960. if (!_this._scene || !_this._scene.getEngine()) {
  65961. return;
  65962. }
  65963. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65964. currentIndex++;
  65965. if (currentIndex >= subMeshes.length) {
  65966. if (onCompiled) {
  65967. onCompiled(_this);
  65968. }
  65969. return;
  65970. }
  65971. }
  65972. setTimeout(checkReady, 16);
  65973. };
  65974. checkReady();
  65975. };
  65976. /**
  65977. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65978. * @param options Sets of optional options forcing the compilation with different modes
  65979. * @returns A promise that resolves when the compilation completes
  65980. */
  65981. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65982. var _this = this;
  65983. return new Promise(function (resolve) {
  65984. _this.forceCompilation(function () {
  65985. resolve();
  65986. }, options);
  65987. });
  65988. };
  65989. /**
  65990. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65991. * @param subMesh The submesh we want to render in the shadow map
  65992. * @param useInstances Defines wether will draw in the map using instances
  65993. * @returns true if ready otherwise, false
  65994. */
  65995. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65996. var defines = [];
  65997. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65998. defines.push("#define FLOAT");
  65999. }
  66000. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66001. defines.push("#define ESM");
  66002. }
  66003. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66004. defines.push("#define DEPTHTEXTURE");
  66005. }
  66006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66007. var mesh = subMesh.getMesh();
  66008. var material = subMesh.getMaterial();
  66009. // Normal bias.
  66010. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66011. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66012. defines.push("#define NORMAL");
  66013. if (mesh.nonUniformScaling) {
  66014. defines.push("#define NONUNIFORMSCALING");
  66015. }
  66016. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66017. defines.push("#define DIRECTIONINLIGHTDATA");
  66018. }
  66019. }
  66020. // Alpha test
  66021. if (material && material.needAlphaTesting()) {
  66022. var alphaTexture = material.getAlphaTestTexture();
  66023. if (alphaTexture) {
  66024. defines.push("#define ALPHATEST");
  66025. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66026. attribs.push(BABYLON.VertexBuffer.UVKind);
  66027. defines.push("#define UV1");
  66028. }
  66029. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66030. if (alphaTexture.coordinatesIndex === 1) {
  66031. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66032. defines.push("#define UV2");
  66033. }
  66034. }
  66035. }
  66036. }
  66037. // Bones
  66038. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66039. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66040. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66041. if (mesh.numBoneInfluencers > 4) {
  66042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66044. }
  66045. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66046. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66047. }
  66048. else {
  66049. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66050. }
  66051. // Morph targets
  66052. var manager = mesh.morphTargetManager;
  66053. var morphInfluencers = 0;
  66054. if (manager) {
  66055. if (manager.numInfluencers > 0) {
  66056. defines.push("#define MORPHTARGETS");
  66057. morphInfluencers = manager.numInfluencers;
  66058. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66059. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66060. }
  66061. }
  66062. // Instances
  66063. if (useInstances) {
  66064. defines.push("#define INSTANCES");
  66065. attribs.push("world0");
  66066. attribs.push("world1");
  66067. attribs.push("world2");
  66068. attribs.push("world3");
  66069. }
  66070. // Get correct effect
  66071. var join = defines.join("\n");
  66072. if (this._cachedDefines !== join) {
  66073. this._cachedDefines = join;
  66074. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66075. }
  66076. if (!this._effect.isReady()) {
  66077. return false;
  66078. }
  66079. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66080. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66081. this._initializeBlurRTTAndPostProcesses();
  66082. }
  66083. }
  66084. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66085. return false;
  66086. }
  66087. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66088. return false;
  66089. }
  66090. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66091. return false;
  66092. }
  66093. return true;
  66094. };
  66095. /**
  66096. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66097. * @param defines Defines of the material we want to update
  66098. * @param lightIndex Index of the light in the enabled light list of the material
  66099. */
  66100. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66101. var scene = this._scene;
  66102. var light = this._light;
  66103. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66104. return;
  66105. }
  66106. defines["SHADOW" + lightIndex] = true;
  66107. if (this.useContactHardeningShadow) {
  66108. defines["SHADOWPCSS" + lightIndex] = true;
  66109. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66110. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66111. }
  66112. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66113. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66114. }
  66115. // else default to high.
  66116. }
  66117. if (this.usePercentageCloserFiltering) {
  66118. defines["SHADOWPCF" + lightIndex] = true;
  66119. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66120. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66121. }
  66122. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66123. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66124. }
  66125. // else default to high.
  66126. }
  66127. else if (this.usePoissonSampling) {
  66128. defines["SHADOWPOISSON" + lightIndex] = true;
  66129. }
  66130. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66131. defines["SHADOWESM" + lightIndex] = true;
  66132. }
  66133. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66134. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66135. }
  66136. if (light.needCube()) {
  66137. defines["SHADOWCUBE" + lightIndex] = true;
  66138. }
  66139. };
  66140. /**
  66141. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66142. * defined in the generator but impacting the effect).
  66143. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66144. * @param effect The effect we are binfing the information for
  66145. */
  66146. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66147. var light = this._light;
  66148. var scene = this._scene;
  66149. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66150. return;
  66151. }
  66152. var camera = scene.activeCamera;
  66153. if (!camera) {
  66154. return;
  66155. }
  66156. var shadowMap = this.getShadowMap();
  66157. if (!shadowMap) {
  66158. return;
  66159. }
  66160. if (!light.needCube()) {
  66161. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66162. }
  66163. // Only PCF uses depth stencil texture.
  66164. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66165. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66166. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66167. }
  66168. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66169. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66170. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66171. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66172. }
  66173. else {
  66174. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66175. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66176. }
  66177. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66178. };
  66179. /**
  66180. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66181. * (eq to shadow prjection matrix * light transform matrix)
  66182. * @returns The transform matrix used to create the shadow map
  66183. */
  66184. ShadowGenerator.prototype.getTransformMatrix = function () {
  66185. var scene = this._scene;
  66186. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66187. return this._transformMatrix;
  66188. }
  66189. this._currentRenderID = scene.getRenderId();
  66190. this._currentFaceIndexCache = this._currentFaceIndex;
  66191. var lightPosition = this._light.position;
  66192. if (this._light.computeTransformedInformation()) {
  66193. lightPosition = this._light.transformedPosition;
  66194. }
  66195. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66196. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66197. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66198. }
  66199. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66200. this._cachedPosition.copyFrom(lightPosition);
  66201. this._cachedDirection.copyFrom(this._lightDirection);
  66202. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66203. var shadowMap = this.getShadowMap();
  66204. if (shadowMap) {
  66205. var renderList = shadowMap.renderList;
  66206. if (renderList) {
  66207. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66208. }
  66209. }
  66210. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66211. }
  66212. return this._transformMatrix;
  66213. };
  66214. /**
  66215. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66216. * Cube and 2D textures for instance.
  66217. */
  66218. ShadowGenerator.prototype.recreateShadowMap = function () {
  66219. var shadowMap = this._shadowMap;
  66220. if (!shadowMap) {
  66221. return;
  66222. }
  66223. // Track render list.
  66224. var renderList = shadowMap.renderList;
  66225. // Clean up existing data.
  66226. this._disposeRTTandPostProcesses();
  66227. // Reinitializes.
  66228. this._initializeGenerator();
  66229. // Reaffect the filter to ensure a correct fallback if necessary.
  66230. this.filter = this.filter;
  66231. // Reaffect the filter.
  66232. this._applyFilterValues();
  66233. // Reaffect Render List.
  66234. this._shadowMap.renderList = renderList;
  66235. };
  66236. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66237. if (this._shadowMap2) {
  66238. this._shadowMap2.dispose();
  66239. this._shadowMap2 = null;
  66240. }
  66241. if (this._boxBlurPostprocess) {
  66242. this._boxBlurPostprocess.dispose();
  66243. this._boxBlurPostprocess = null;
  66244. }
  66245. if (this._kernelBlurXPostprocess) {
  66246. this._kernelBlurXPostprocess.dispose();
  66247. this._kernelBlurXPostprocess = null;
  66248. }
  66249. if (this._kernelBlurYPostprocess) {
  66250. this._kernelBlurYPostprocess.dispose();
  66251. this._kernelBlurYPostprocess = null;
  66252. }
  66253. this._blurPostProcesses = [];
  66254. };
  66255. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66256. if (this._shadowMap) {
  66257. this._shadowMap.dispose();
  66258. this._shadowMap = null;
  66259. }
  66260. this._disposeBlurPostProcesses();
  66261. };
  66262. /**
  66263. * Disposes the ShadowGenerator.
  66264. * Returns nothing.
  66265. */
  66266. ShadowGenerator.prototype.dispose = function () {
  66267. this._disposeRTTandPostProcesses();
  66268. if (this._light) {
  66269. this._light._shadowGenerator = null;
  66270. this._light._markMeshesAsLightDirty();
  66271. }
  66272. };
  66273. /**
  66274. * Serializes the shadow generator setup to a json object.
  66275. * @returns The serialized JSON object
  66276. */
  66277. ShadowGenerator.prototype.serialize = function () {
  66278. var serializationObject = {};
  66279. var shadowMap = this.getShadowMap();
  66280. if (!shadowMap) {
  66281. return serializationObject;
  66282. }
  66283. serializationObject.lightId = this._light.id;
  66284. serializationObject.mapSize = shadowMap.getRenderSize();
  66285. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66286. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66287. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66288. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66289. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66290. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66291. serializationObject.depthScale = this.depthScale;
  66292. serializationObject.darkness = this.getDarkness();
  66293. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66294. serializationObject.blurKernel = this.blurKernel;
  66295. serializationObject.blurScale = this.blurScale;
  66296. serializationObject.useKernelBlur = this.useKernelBlur;
  66297. serializationObject.transparencyShadow = this._transparencyShadow;
  66298. serializationObject.bias = this.bias;
  66299. serializationObject.normalBias = this.normalBias;
  66300. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66301. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66302. serializationObject.filteringQuality = this.filteringQuality;
  66303. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66304. serializationObject.renderList = [];
  66305. if (shadowMap.renderList) {
  66306. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66307. var mesh = shadowMap.renderList[meshIndex];
  66308. serializationObject.renderList.push(mesh.id);
  66309. }
  66310. }
  66311. return serializationObject;
  66312. };
  66313. /**
  66314. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66315. * @param parsedShadowGenerator The JSON object to parse
  66316. * @param scene The scene to create the shadow map for
  66317. * @returns The parsed shadow generator
  66318. */
  66319. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66320. //casting to point light, as light is missing the position attr and typescript complains.
  66321. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66322. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66323. var shadowMap = shadowGenerator.getShadowMap();
  66324. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66325. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66326. meshes.forEach(function (mesh) {
  66327. if (!shadowMap) {
  66328. return;
  66329. }
  66330. if (!shadowMap.renderList) {
  66331. shadowMap.renderList = [];
  66332. }
  66333. shadowMap.renderList.push(mesh);
  66334. });
  66335. }
  66336. if (parsedShadowGenerator.usePoissonSampling) {
  66337. shadowGenerator.usePoissonSampling = true;
  66338. }
  66339. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66340. shadowGenerator.useExponentialShadowMap = true;
  66341. }
  66342. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66343. shadowGenerator.useBlurExponentialShadowMap = true;
  66344. }
  66345. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66346. shadowGenerator.useCloseExponentialShadowMap = true;
  66347. }
  66348. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66349. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66350. }
  66351. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66352. shadowGenerator.usePercentageCloserFiltering = true;
  66353. }
  66354. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66355. shadowGenerator.useContactHardeningShadow = true;
  66356. }
  66357. if (parsedShadowGenerator.filteringQuality) {
  66358. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66359. }
  66360. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66361. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66362. }
  66363. // Backward compat
  66364. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66365. shadowGenerator.useExponentialShadowMap = true;
  66366. }
  66367. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66368. shadowGenerator.useBlurExponentialShadowMap = true;
  66369. }
  66370. if (parsedShadowGenerator.depthScale) {
  66371. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66372. }
  66373. if (parsedShadowGenerator.blurScale) {
  66374. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66375. }
  66376. if (parsedShadowGenerator.blurBoxOffset) {
  66377. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66378. }
  66379. if (parsedShadowGenerator.useKernelBlur) {
  66380. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66381. }
  66382. if (parsedShadowGenerator.blurKernel) {
  66383. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66384. }
  66385. if (parsedShadowGenerator.bias !== undefined) {
  66386. shadowGenerator.bias = parsedShadowGenerator.bias;
  66387. }
  66388. if (parsedShadowGenerator.normalBias !== undefined) {
  66389. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66390. }
  66391. if (parsedShadowGenerator.darkness) {
  66392. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66393. }
  66394. if (parsedShadowGenerator.transparencyShadow) {
  66395. shadowGenerator.setTransparencyShadow(true);
  66396. }
  66397. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66398. return shadowGenerator;
  66399. };
  66400. /**
  66401. * Shadow generator mode None: no filtering applied.
  66402. */
  66403. ShadowGenerator.FILTER_NONE = 0;
  66404. /**
  66405. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66406. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66407. */
  66408. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66409. /**
  66410. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66411. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66412. */
  66413. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66414. /**
  66415. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66416. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66417. */
  66418. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66419. /**
  66420. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66421. * edge artifacts on steep falloff.
  66422. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66423. */
  66424. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66425. /**
  66426. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66427. * edge artifacts on steep falloff.
  66428. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66429. */
  66430. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66431. /**
  66432. * Shadow generator mode PCF: Percentage Closer Filtering
  66433. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66434. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66435. */
  66436. ShadowGenerator.FILTER_PCF = 6;
  66437. /**
  66438. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66439. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66440. * Contact Hardening
  66441. */
  66442. ShadowGenerator.FILTER_PCSS = 7;
  66443. /**
  66444. * Reserved for PCF and PCSS
  66445. * Highest Quality.
  66446. *
  66447. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66448. *
  66449. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66450. */
  66451. ShadowGenerator.QUALITY_HIGH = 0;
  66452. /**
  66453. * Reserved for PCF and PCSS
  66454. * Good tradeoff for quality/perf cross devices
  66455. *
  66456. * Execute PCF on a 3*3 kernel.
  66457. *
  66458. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66459. */
  66460. ShadowGenerator.QUALITY_MEDIUM = 1;
  66461. /**
  66462. * Reserved for PCF and PCSS
  66463. * The lowest quality but the fastest.
  66464. *
  66465. * Execute PCF on a 1*1 kernel.
  66466. *
  66467. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66468. */
  66469. ShadowGenerator.QUALITY_LOW = 2;
  66470. return ShadowGenerator;
  66471. }());
  66472. BABYLON.ShadowGenerator = ShadowGenerator;
  66473. })(BABYLON || (BABYLON = {}));
  66474. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66475. var BABYLON;
  66476. (function (BABYLON) {
  66477. var DefaultLoadingScreen = /** @class */ (function () {
  66478. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66479. if (_loadingText === void 0) { _loadingText = ""; }
  66480. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66481. var _this = this;
  66482. this._renderingCanvas = _renderingCanvas;
  66483. this._loadingText = _loadingText;
  66484. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66485. // Resize
  66486. this._resizeLoadingUI = function () {
  66487. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66488. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66489. if (!_this._loadingDiv) {
  66490. return;
  66491. }
  66492. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66493. _this._loadingDiv.style.left = canvasRect.left + "px";
  66494. _this._loadingDiv.style.top = canvasRect.top + "px";
  66495. _this._loadingDiv.style.width = canvasRect.width + "px";
  66496. _this._loadingDiv.style.height = canvasRect.height + "px";
  66497. };
  66498. }
  66499. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66500. if (this._loadingDiv) {
  66501. // Do not add a loading screen if there is already one
  66502. return;
  66503. }
  66504. this._loadingDiv = document.createElement("div");
  66505. this._loadingDiv.id = "babylonjsLoadingDiv";
  66506. this._loadingDiv.style.opacity = "0";
  66507. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66508. this._loadingDiv.style.pointerEvents = "none";
  66509. // Loading text
  66510. this._loadingTextDiv = document.createElement("div");
  66511. this._loadingTextDiv.style.position = "absolute";
  66512. this._loadingTextDiv.style.left = "0";
  66513. this._loadingTextDiv.style.top = "50%";
  66514. this._loadingTextDiv.style.marginTop = "80px";
  66515. this._loadingTextDiv.style.width = "100%";
  66516. this._loadingTextDiv.style.height = "20px";
  66517. this._loadingTextDiv.style.fontFamily = "Arial";
  66518. this._loadingTextDiv.style.fontSize = "14px";
  66519. this._loadingTextDiv.style.color = "white";
  66520. this._loadingTextDiv.style.textAlign = "center";
  66521. this._loadingTextDiv.innerHTML = "Loading";
  66522. this._loadingDiv.appendChild(this._loadingTextDiv);
  66523. //set the predefined text
  66524. this._loadingTextDiv.innerHTML = this._loadingText;
  66525. // Generating keyframes
  66526. var style = document.createElement('style');
  66527. style.type = 'text/css';
  66528. 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 }";
  66529. style.innerHTML = keyFrames;
  66530. document.getElementsByTagName('head')[0].appendChild(style);
  66531. // Loading img
  66532. var imgBack = new Image();
  66533. 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";
  66534. imgBack.style.position = "absolute";
  66535. imgBack.style.left = "50%";
  66536. imgBack.style.top = "50%";
  66537. imgBack.style.marginLeft = "-60px";
  66538. imgBack.style.marginTop = "-60px";
  66539. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66540. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66541. imgBack.style.transformOrigin = "50% 50%";
  66542. imgBack.style.webkitTransformOrigin = "50% 50%";
  66543. this._loadingDiv.appendChild(imgBack);
  66544. this._resizeLoadingUI();
  66545. window.addEventListener("resize", this._resizeLoadingUI);
  66546. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66547. document.body.appendChild(this._loadingDiv);
  66548. this._loadingDiv.style.opacity = "1";
  66549. };
  66550. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66551. var _this = this;
  66552. if (!this._loadingDiv) {
  66553. return;
  66554. }
  66555. var onTransitionEnd = function () {
  66556. if (!_this._loadingDiv) {
  66557. return;
  66558. }
  66559. document.body.removeChild(_this._loadingDiv);
  66560. window.removeEventListener("resize", _this._resizeLoadingUI);
  66561. _this._loadingDiv = null;
  66562. };
  66563. this._loadingDiv.style.opacity = "0";
  66564. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66565. };
  66566. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66567. set: function (text) {
  66568. this._loadingText = text;
  66569. if (this._loadingTextDiv) {
  66570. this._loadingTextDiv.innerHTML = this._loadingText;
  66571. }
  66572. },
  66573. enumerable: true,
  66574. configurable: true
  66575. });
  66576. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66577. get: function () {
  66578. return this._loadingDivBackgroundColor;
  66579. },
  66580. set: function (color) {
  66581. this._loadingDivBackgroundColor = color;
  66582. if (!this._loadingDiv) {
  66583. return;
  66584. }
  66585. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66586. },
  66587. enumerable: true,
  66588. configurable: true
  66589. });
  66590. return DefaultLoadingScreen;
  66591. }());
  66592. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66593. })(BABYLON || (BABYLON = {}));
  66594. //# sourceMappingURL=babylon.loadingScreen.js.map
  66595. var BABYLON;
  66596. (function (BABYLON) {
  66597. var SceneLoaderProgressEvent = /** @class */ (function () {
  66598. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66599. this.lengthComputable = lengthComputable;
  66600. this.loaded = loaded;
  66601. this.total = total;
  66602. }
  66603. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66604. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66605. };
  66606. return SceneLoaderProgressEvent;
  66607. }());
  66608. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66609. var SceneLoader = /** @class */ (function () {
  66610. function SceneLoader() {
  66611. }
  66612. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66613. get: function () {
  66614. return 0;
  66615. },
  66616. enumerable: true,
  66617. configurable: true
  66618. });
  66619. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66620. get: function () {
  66621. return 1;
  66622. },
  66623. enumerable: true,
  66624. configurable: true
  66625. });
  66626. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66627. get: function () {
  66628. return 2;
  66629. },
  66630. enumerable: true,
  66631. configurable: true
  66632. });
  66633. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66634. get: function () {
  66635. return 3;
  66636. },
  66637. enumerable: true,
  66638. configurable: true
  66639. });
  66640. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66641. get: function () {
  66642. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66643. },
  66644. set: function (value) {
  66645. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66646. },
  66647. enumerable: true,
  66648. configurable: true
  66649. });
  66650. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66651. get: function () {
  66652. return SceneLoader._ShowLoadingScreen;
  66653. },
  66654. set: function (value) {
  66655. SceneLoader._ShowLoadingScreen = value;
  66656. },
  66657. enumerable: true,
  66658. configurable: true
  66659. });
  66660. Object.defineProperty(SceneLoader, "loggingLevel", {
  66661. get: function () {
  66662. return SceneLoader._loggingLevel;
  66663. },
  66664. set: function (value) {
  66665. SceneLoader._loggingLevel = value;
  66666. },
  66667. enumerable: true,
  66668. configurable: true
  66669. });
  66670. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66671. get: function () {
  66672. return SceneLoader._CleanBoneMatrixWeights;
  66673. },
  66674. set: function (value) {
  66675. SceneLoader._CleanBoneMatrixWeights = value;
  66676. },
  66677. enumerable: true,
  66678. configurable: true
  66679. });
  66680. SceneLoader._getDefaultPlugin = function () {
  66681. return SceneLoader._registeredPlugins[".babylon"];
  66682. };
  66683. SceneLoader._getPluginForExtension = function (extension) {
  66684. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66685. if (registeredPlugin) {
  66686. return registeredPlugin;
  66687. }
  66688. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66689. return SceneLoader._getDefaultPlugin();
  66690. };
  66691. SceneLoader._getPluginForDirectLoad = function (data) {
  66692. for (var extension in SceneLoader._registeredPlugins) {
  66693. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66694. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66695. return SceneLoader._registeredPlugins[extension];
  66696. }
  66697. }
  66698. return SceneLoader._getDefaultPlugin();
  66699. };
  66700. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66701. if (sceneFilename.name) {
  66702. sceneFilename = sceneFilename.name;
  66703. }
  66704. var queryStringPosition = sceneFilename.indexOf("?");
  66705. if (queryStringPosition !== -1) {
  66706. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66707. }
  66708. var dotPosition = sceneFilename.lastIndexOf(".");
  66709. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66710. return SceneLoader._getPluginForExtension(extension);
  66711. };
  66712. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66713. SceneLoader._getDirectLoad = function (sceneFilename) {
  66714. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66715. return sceneFilename.substr(5);
  66716. }
  66717. return null;
  66718. };
  66719. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66720. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66721. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66722. var plugin;
  66723. if (registeredPlugin.plugin.createPlugin) {
  66724. plugin = registeredPlugin.plugin.createPlugin();
  66725. }
  66726. else {
  66727. plugin = registeredPlugin.plugin;
  66728. }
  66729. var useArrayBuffer = registeredPlugin.isBinary;
  66730. var database;
  66731. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66732. var dataCallback = function (data, responseURL) {
  66733. if (scene.isDisposed) {
  66734. onError("Scene has been disposed");
  66735. return;
  66736. }
  66737. scene.database = database;
  66738. onSuccess(plugin, data, responseURL);
  66739. };
  66740. var request = null;
  66741. var pluginDisposed = false;
  66742. var onDisposeObservable = plugin.onDisposeObservable;
  66743. if (onDisposeObservable) {
  66744. onDisposeObservable.add(function () {
  66745. pluginDisposed = true;
  66746. if (request) {
  66747. request.abort();
  66748. request = null;
  66749. }
  66750. onDispose();
  66751. });
  66752. }
  66753. var manifestChecked = function () {
  66754. if (pluginDisposed) {
  66755. return;
  66756. }
  66757. var url = rootUrl + sceneFilename;
  66758. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66759. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66760. } : undefined, database, useArrayBuffer, function (request, exception) {
  66761. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66762. });
  66763. };
  66764. if (directLoad) {
  66765. dataCallback(directLoad);
  66766. return plugin;
  66767. }
  66768. if (rootUrl.indexOf("file:") === -1) {
  66769. var engine = scene.getEngine();
  66770. var canUseOfflineSupport = engine.enableOfflineSupport;
  66771. if (canUseOfflineSupport) {
  66772. // Also check for exceptions
  66773. var exceptionFound = false;
  66774. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66775. var regex = _a[_i];
  66776. if (regex.test(rootUrl + sceneFilename)) {
  66777. exceptionFound = true;
  66778. break;
  66779. }
  66780. }
  66781. canUseOfflineSupport = !exceptionFound;
  66782. }
  66783. if (canUseOfflineSupport) {
  66784. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66785. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66786. }
  66787. else {
  66788. manifestChecked();
  66789. }
  66790. }
  66791. // Loading file from disk via input file or drag'n'drop
  66792. else {
  66793. var fileOrString = sceneFilename;
  66794. if (fileOrString.name) { // File
  66795. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66796. }
  66797. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66798. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66799. }
  66800. else {
  66801. onError("Unable to find file named " + sceneFilename);
  66802. }
  66803. }
  66804. return plugin;
  66805. };
  66806. // Public functions
  66807. SceneLoader.GetPluginForExtension = function (extension) {
  66808. return SceneLoader._getPluginForExtension(extension).plugin;
  66809. };
  66810. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66811. return !!SceneLoader._registeredPlugins[extension];
  66812. };
  66813. SceneLoader.RegisterPlugin = function (plugin) {
  66814. if (typeof plugin.extensions === "string") {
  66815. var extension = plugin.extensions;
  66816. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66817. plugin: plugin,
  66818. isBinary: false
  66819. };
  66820. }
  66821. else {
  66822. var extensions = plugin.extensions;
  66823. Object.keys(extensions).forEach(function (extension) {
  66824. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66825. plugin: plugin,
  66826. isBinary: extensions[extension].isBinary
  66827. };
  66828. });
  66829. }
  66830. };
  66831. /**
  66832. * Import meshes into a scene
  66833. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66834. * @param rootUrl a string that defines the root url for scene and resources
  66835. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66836. * @param scene the instance of BABYLON.Scene to append to
  66837. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66838. * @param onProgress a callback with a progress event for each file being loaded
  66839. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66840. * @param pluginExtension the extension used to determine the plugin
  66841. * @returns The loaded plugin
  66842. */
  66843. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66844. if (onSuccess === void 0) { onSuccess = null; }
  66845. if (onProgress === void 0) { onProgress = null; }
  66846. if (onError === void 0) { onError = null; }
  66847. if (pluginExtension === void 0) { pluginExtension = null; }
  66848. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66849. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66850. return null;
  66851. }
  66852. var loadingToken = {};
  66853. scene._addPendingData(loadingToken);
  66854. var disposeHandler = function () {
  66855. scene._removePendingData(loadingToken);
  66856. };
  66857. var errorHandler = function (message, exception) {
  66858. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66859. if (onError) {
  66860. onError(scene, errorMessage, exception);
  66861. }
  66862. else {
  66863. BABYLON.Tools.Error(errorMessage);
  66864. // should the exception be thrown?
  66865. }
  66866. disposeHandler();
  66867. };
  66868. var progressHandler = onProgress ? function (event) {
  66869. try {
  66870. onProgress(event);
  66871. }
  66872. catch (e) {
  66873. errorHandler("Error in onProgress callback", e);
  66874. }
  66875. } : undefined;
  66876. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66877. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66878. if (onSuccess) {
  66879. try {
  66880. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66881. }
  66882. catch (e) {
  66883. errorHandler("Error in onSuccess callback", e);
  66884. }
  66885. }
  66886. scene._removePendingData(loadingToken);
  66887. };
  66888. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66889. if (plugin.rewriteRootURL) {
  66890. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66891. }
  66892. if (sceneFilename === "") {
  66893. if (sceneFilename === "") {
  66894. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66895. }
  66896. }
  66897. if (plugin.importMesh) {
  66898. var syncedPlugin = plugin;
  66899. var meshes = new Array();
  66900. var particleSystems = new Array();
  66901. var skeletons = new Array();
  66902. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66903. return;
  66904. }
  66905. scene.loadingPluginName = plugin.name;
  66906. successHandler(meshes, particleSystems, skeletons, []);
  66907. }
  66908. else {
  66909. var asyncedPlugin = plugin;
  66910. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66911. scene.loadingPluginName = plugin.name;
  66912. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66913. }).catch(function (error) {
  66914. errorHandler(error.message, error);
  66915. });
  66916. }
  66917. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66918. };
  66919. /**
  66920. * Import meshes into a scene
  66921. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66922. * @param rootUrl a string that defines the root url for scene and resources
  66923. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66924. * @param scene the instance of BABYLON.Scene to append to
  66925. * @param onProgress a callback with a progress event for each file being loaded
  66926. * @param pluginExtension the extension used to determine the plugin
  66927. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66928. */
  66929. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66930. if (onProgress === void 0) { onProgress = null; }
  66931. if (pluginExtension === void 0) { pluginExtension = null; }
  66932. return new Promise(function (resolve, reject) {
  66933. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66934. resolve({
  66935. meshes: meshes,
  66936. particleSystems: particleSystems,
  66937. skeletons: skeletons,
  66938. animationGroups: animationGroups
  66939. });
  66940. }, onProgress, function (scene, message, exception) {
  66941. reject(exception || new Error(message));
  66942. });
  66943. });
  66944. };
  66945. /**
  66946. * Load a scene
  66947. * @param rootUrl a string that defines the root url for scene and resources
  66948. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66949. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66950. * @param onSuccess a callback with the scene when import succeeds
  66951. * @param onProgress a callback with a progress event for each file being loaded
  66952. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66953. * @param pluginExtension the extension used to determine the plugin
  66954. * @returns The loaded plugin
  66955. */
  66956. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66957. if (onSuccess === void 0) { onSuccess = null; }
  66958. if (onProgress === void 0) { onProgress = null; }
  66959. if (onError === void 0) { onError = null; }
  66960. if (pluginExtension === void 0) { pluginExtension = null; }
  66961. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66962. };
  66963. /**
  66964. * Load a scene
  66965. * @param rootUrl a string that defines the root url for scene and resources
  66966. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66967. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66968. * @param onProgress a callback with a progress event for each file being loaded
  66969. * @param pluginExtension the extension used to determine the plugin
  66970. * @returns The loaded scene
  66971. */
  66972. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66973. if (onProgress === void 0) { onProgress = null; }
  66974. if (pluginExtension === void 0) { pluginExtension = null; }
  66975. return new Promise(function (resolve, reject) {
  66976. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66977. resolve(scene);
  66978. }, onProgress, function (scene, message, exception) {
  66979. reject(exception || new Error(message));
  66980. }, pluginExtension);
  66981. });
  66982. };
  66983. /**
  66984. * Append a scene
  66985. * @param rootUrl a string that defines the root url for scene and resources
  66986. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66987. * @param scene is the instance of BABYLON.Scene to append to
  66988. * @param onSuccess a callback with the scene when import succeeds
  66989. * @param onProgress a callback with a progress event for each file being loaded
  66990. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66991. * @param pluginExtension the extension used to determine the plugin
  66992. * @returns The loaded plugin
  66993. */
  66994. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66995. if (onSuccess === void 0) { onSuccess = null; }
  66996. if (onProgress === void 0) { onProgress = null; }
  66997. if (onError === void 0) { onError = null; }
  66998. if (pluginExtension === void 0) { pluginExtension = null; }
  66999. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67000. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67001. return null;
  67002. }
  67003. if (SceneLoader.ShowLoadingScreen) {
  67004. scene.getEngine().displayLoadingUI();
  67005. }
  67006. var loadingToken = {};
  67007. scene._addPendingData(loadingToken);
  67008. var disposeHandler = function () {
  67009. scene._removePendingData(loadingToken);
  67010. scene.getEngine().hideLoadingUI();
  67011. };
  67012. var errorHandler = function (message, exception) {
  67013. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67014. if (onError) {
  67015. onError(scene, errorMessage, exception);
  67016. }
  67017. else {
  67018. BABYLON.Tools.Error(errorMessage);
  67019. // should the exception be thrown?
  67020. }
  67021. disposeHandler();
  67022. };
  67023. var progressHandler = onProgress ? function (event) {
  67024. try {
  67025. onProgress(event);
  67026. }
  67027. catch (e) {
  67028. errorHandler("Error in onProgress callback", e);
  67029. }
  67030. } : undefined;
  67031. var successHandler = function () {
  67032. if (onSuccess) {
  67033. try {
  67034. onSuccess(scene);
  67035. }
  67036. catch (e) {
  67037. errorHandler("Error in onSuccess callback", e);
  67038. }
  67039. }
  67040. scene._removePendingData(loadingToken);
  67041. };
  67042. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67043. if (sceneFilename === "") {
  67044. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67045. }
  67046. if (plugin.load) {
  67047. var syncedPlugin = plugin;
  67048. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67049. return;
  67050. }
  67051. scene.loadingPluginName = plugin.name;
  67052. successHandler();
  67053. }
  67054. else {
  67055. var asyncedPlugin = plugin;
  67056. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67057. scene.loadingPluginName = plugin.name;
  67058. successHandler();
  67059. }).catch(function (error) {
  67060. errorHandler(error.message, error);
  67061. });
  67062. }
  67063. if (SceneLoader.ShowLoadingScreen) {
  67064. scene.executeWhenReady(function () {
  67065. scene.getEngine().hideLoadingUI();
  67066. });
  67067. }
  67068. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67069. };
  67070. /**
  67071. * Append a scene
  67072. * @param rootUrl a string that defines the root url for scene and resources
  67073. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67074. * @param scene is the instance of BABYLON.Scene to append to
  67075. * @param onProgress a callback with a progress event for each file being loaded
  67076. * @param pluginExtension the extension used to determine the plugin
  67077. * @returns The given scene
  67078. */
  67079. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67080. if (onProgress === void 0) { onProgress = null; }
  67081. if (pluginExtension === void 0) { pluginExtension = null; }
  67082. return new Promise(function (resolve, reject) {
  67083. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67084. resolve(scene);
  67085. }, onProgress, function (scene, message, exception) {
  67086. reject(exception || new Error(message));
  67087. }, pluginExtension);
  67088. });
  67089. };
  67090. /**
  67091. * Load a scene into an asset container
  67092. * @param rootUrl a string that defines the root url for scene and resources
  67093. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67094. * @param scene is the instance of BABYLON.Scene to append to
  67095. * @param onSuccess a callback with the scene when import succeeds
  67096. * @param onProgress a callback with a progress event for each file being loaded
  67097. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67098. * @param pluginExtension the extension used to determine the plugin
  67099. * @returns The loaded plugin
  67100. */
  67101. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67102. if (onSuccess === void 0) { onSuccess = null; }
  67103. if (onProgress === void 0) { onProgress = null; }
  67104. if (onError === void 0) { onError = null; }
  67105. if (pluginExtension === void 0) { pluginExtension = null; }
  67106. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67107. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67108. return null;
  67109. }
  67110. var loadingToken = {};
  67111. scene._addPendingData(loadingToken);
  67112. var disposeHandler = function () {
  67113. scene._removePendingData(loadingToken);
  67114. };
  67115. var errorHandler = function (message, exception) {
  67116. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67117. if (onError) {
  67118. onError(scene, errorMessage, exception);
  67119. }
  67120. else {
  67121. BABYLON.Tools.Error(errorMessage);
  67122. // should the exception be thrown?
  67123. }
  67124. disposeHandler();
  67125. };
  67126. var progressHandler = onProgress ? function (event) {
  67127. try {
  67128. onProgress(event);
  67129. }
  67130. catch (e) {
  67131. errorHandler("Error in onProgress callback", e);
  67132. }
  67133. } : undefined;
  67134. var successHandler = function (assets) {
  67135. if (onSuccess) {
  67136. try {
  67137. onSuccess(assets);
  67138. }
  67139. catch (e) {
  67140. errorHandler("Error in onSuccess callback", e);
  67141. }
  67142. }
  67143. scene._removePendingData(loadingToken);
  67144. };
  67145. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67146. if (plugin.loadAssetContainer) {
  67147. var syncedPlugin = plugin;
  67148. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67149. if (!assetContainer) {
  67150. return;
  67151. }
  67152. scene.loadingPluginName = plugin.name;
  67153. successHandler(assetContainer);
  67154. }
  67155. else if (plugin.loadAssetContainerAsync) {
  67156. var asyncedPlugin = plugin;
  67157. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67158. scene.loadingPluginName = plugin.name;
  67159. successHandler(assetContainer);
  67160. }).catch(function (error) {
  67161. errorHandler(error.message, error);
  67162. });
  67163. }
  67164. else {
  67165. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67166. }
  67167. if (SceneLoader.ShowLoadingScreen) {
  67168. scene.executeWhenReady(function () {
  67169. scene.getEngine().hideLoadingUI();
  67170. });
  67171. }
  67172. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67173. };
  67174. /**
  67175. * Load a scene into an asset container
  67176. * @param rootUrl a string that defines the root url for scene and resources
  67177. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67178. * @param scene is the instance of BABYLON.Scene to append to
  67179. * @param onProgress a callback with a progress event for each file being loaded
  67180. * @param pluginExtension the extension used to determine the plugin
  67181. * @returns The loaded asset container
  67182. */
  67183. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67184. if (onProgress === void 0) { onProgress = null; }
  67185. if (pluginExtension === void 0) { pluginExtension = null; }
  67186. return new Promise(function (resolve, reject) {
  67187. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67188. resolve(assetContainer);
  67189. }, onProgress, function (scene, message, exception) {
  67190. reject(exception || new Error(message));
  67191. }, pluginExtension);
  67192. });
  67193. };
  67194. // Flags
  67195. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67196. SceneLoader._ShowLoadingScreen = true;
  67197. SceneLoader._CleanBoneMatrixWeights = false;
  67198. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67199. // Members
  67200. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67201. SceneLoader._registeredPlugins = {};
  67202. return SceneLoader;
  67203. }());
  67204. BABYLON.SceneLoader = SceneLoader;
  67205. ;
  67206. })(BABYLON || (BABYLON = {}));
  67207. //# sourceMappingURL=babylon.sceneLoader.js.map
  67208. var BABYLON;
  67209. (function (BABYLON) {
  67210. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67211. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67212. var parsedMaterial = parsedData.materials[index];
  67213. if (parsedMaterial.id === id) {
  67214. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67215. }
  67216. }
  67217. return null;
  67218. };
  67219. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67220. for (var i in names) {
  67221. if (mesh.name === names[i]) {
  67222. hierarchyIds.push(mesh.id);
  67223. return true;
  67224. }
  67225. }
  67226. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67227. hierarchyIds.push(mesh.id);
  67228. return true;
  67229. }
  67230. return false;
  67231. };
  67232. var logOperation = function (operation, producer) {
  67233. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67234. };
  67235. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67236. if (addToScene === void 0) { addToScene = false; }
  67237. var container = new BABYLON.AssetContainer(scene);
  67238. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67239. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67240. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67241. // and avoid problems with multiple concurrent .babylon loads.
  67242. var log = "importScene has failed JSON parse";
  67243. try {
  67244. var parsedData = JSON.parse(data);
  67245. log = "";
  67246. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67247. var index;
  67248. var cache;
  67249. // Lights
  67250. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67251. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67252. var parsedLight = parsedData.lights[index];
  67253. var light = BABYLON.Light.Parse(parsedLight, scene);
  67254. if (light) {
  67255. container.lights.push(light);
  67256. log += (index === 0 ? "\n\tLights:" : "");
  67257. log += "\n\t\t" + light.toString(fullDetails);
  67258. }
  67259. }
  67260. }
  67261. // Animations
  67262. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67263. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67264. var parsedAnimation = parsedData.animations[index];
  67265. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67266. scene.animations.push(animation);
  67267. container.animations.push(animation);
  67268. log += (index === 0 ? "\n\tAnimations:" : "");
  67269. log += "\n\t\t" + animation.toString(fullDetails);
  67270. }
  67271. }
  67272. // Materials
  67273. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67274. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67275. var parsedMaterial = parsedData.materials[index];
  67276. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67277. container.materials.push(mat);
  67278. log += (index === 0 ? "\n\tMaterials:" : "");
  67279. log += "\n\t\t" + mat.toString(fullDetails);
  67280. }
  67281. }
  67282. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67283. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67284. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67285. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67286. container.multiMaterials.push(mmat);
  67287. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67288. log += "\n\t\t" + mmat.toString(fullDetails);
  67289. }
  67290. }
  67291. // Morph targets
  67292. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67293. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67294. var managerData = _a[_i];
  67295. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67296. }
  67297. }
  67298. // Skeletons
  67299. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67300. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67301. var parsedSkeleton = parsedData.skeletons[index];
  67302. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67303. container.skeletons.push(skeleton);
  67304. log += (index === 0 ? "\n\tSkeletons:" : "");
  67305. log += "\n\t\t" + skeleton.toString(fullDetails);
  67306. }
  67307. }
  67308. // Geometries
  67309. var geometries = parsedData.geometries;
  67310. if (geometries !== undefined && geometries !== null) {
  67311. var addedGeometry = new Array();
  67312. // Boxes
  67313. var boxes = geometries.boxes;
  67314. if (boxes !== undefined && boxes !== null) {
  67315. for (index = 0, cache = boxes.length; index < cache; index++) {
  67316. var parsedBox = boxes[index];
  67317. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67318. }
  67319. }
  67320. // Spheres
  67321. var spheres = geometries.spheres;
  67322. if (spheres !== undefined && spheres !== null) {
  67323. for (index = 0, cache = spheres.length; index < cache; index++) {
  67324. var parsedSphere = spheres[index];
  67325. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67326. }
  67327. }
  67328. // Cylinders
  67329. var cylinders = geometries.cylinders;
  67330. if (cylinders !== undefined && cylinders !== null) {
  67331. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67332. var parsedCylinder = cylinders[index];
  67333. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67334. }
  67335. }
  67336. // Toruses
  67337. var toruses = geometries.toruses;
  67338. if (toruses !== undefined && toruses !== null) {
  67339. for (index = 0, cache = toruses.length; index < cache; index++) {
  67340. var parsedTorus = toruses[index];
  67341. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67342. }
  67343. }
  67344. // Grounds
  67345. var grounds = geometries.grounds;
  67346. if (grounds !== undefined && grounds !== null) {
  67347. for (index = 0, cache = grounds.length; index < cache; index++) {
  67348. var parsedGround = grounds[index];
  67349. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67350. }
  67351. }
  67352. // Planes
  67353. var planes = geometries.planes;
  67354. if (planes !== undefined && planes !== null) {
  67355. for (index = 0, cache = planes.length; index < cache; index++) {
  67356. var parsedPlane = planes[index];
  67357. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67358. }
  67359. }
  67360. // TorusKnots
  67361. var torusKnots = geometries.torusKnots;
  67362. if (torusKnots !== undefined && torusKnots !== null) {
  67363. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67364. var parsedTorusKnot = torusKnots[index];
  67365. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67366. }
  67367. }
  67368. // VertexData
  67369. var vertexData = geometries.vertexData;
  67370. if (vertexData !== undefined && vertexData !== null) {
  67371. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67372. var parsedVertexData = vertexData[index];
  67373. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67374. }
  67375. }
  67376. addedGeometry.forEach(function (g) {
  67377. if (g) {
  67378. container.geometries.push(g);
  67379. }
  67380. });
  67381. }
  67382. // Transform nodes
  67383. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67384. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67385. var parsedTransformNode = parsedData.transformNodes[index];
  67386. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67387. container.transformNodes.push(node);
  67388. }
  67389. }
  67390. // Meshes
  67391. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67392. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67393. var parsedMesh = parsedData.meshes[index];
  67394. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67395. container.meshes.push(mesh);
  67396. log += (index === 0 ? "\n\tMeshes:" : "");
  67397. log += "\n\t\t" + mesh.toString(fullDetails);
  67398. }
  67399. }
  67400. // Cameras
  67401. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67402. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67403. var parsedCamera = parsedData.cameras[index];
  67404. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67405. container.cameras.push(camera);
  67406. log += (index === 0 ? "\n\tCameras:" : "");
  67407. log += "\n\t\t" + camera.toString(fullDetails);
  67408. }
  67409. }
  67410. // Browsing all the graph to connect the dots
  67411. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67412. var camera = scene.cameras[index];
  67413. if (camera._waitingParentId) {
  67414. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67415. camera._waitingParentId = null;
  67416. }
  67417. }
  67418. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67419. var light_1 = scene.lights[index];
  67420. if (light_1 && light_1._waitingParentId) {
  67421. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67422. light_1._waitingParentId = null;
  67423. }
  67424. }
  67425. // Sounds
  67426. // TODO: add sound
  67427. var loadedSounds = [];
  67428. var loadedSound;
  67429. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67430. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67431. var parsedSound = parsedData.sounds[index];
  67432. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67433. if (!parsedSound.url)
  67434. parsedSound.url = parsedSound.name;
  67435. if (!loadedSounds[parsedSound.url]) {
  67436. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67437. loadedSounds[parsedSound.url] = loadedSound;
  67438. container.sounds.push(loadedSound);
  67439. }
  67440. else {
  67441. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67442. }
  67443. }
  67444. else {
  67445. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67446. }
  67447. }
  67448. }
  67449. loadedSounds = [];
  67450. // Connect parents & children and parse actions
  67451. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67452. var transformNode = scene.transformNodes[index];
  67453. if (transformNode._waitingParentId) {
  67454. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67455. transformNode._waitingParentId = null;
  67456. }
  67457. }
  67458. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67459. var mesh = scene.meshes[index];
  67460. if (mesh._waitingParentId) {
  67461. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67462. mesh._waitingParentId = null;
  67463. }
  67464. if (mesh._waitingActions) {
  67465. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67466. mesh._waitingActions = null;
  67467. }
  67468. }
  67469. // freeze world matrix application
  67470. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67471. var currentMesh = scene.meshes[index];
  67472. if (currentMesh._waitingFreezeWorldMatrix) {
  67473. currentMesh.freezeWorldMatrix();
  67474. currentMesh._waitingFreezeWorldMatrix = null;
  67475. }
  67476. else {
  67477. currentMesh.computeWorldMatrix(true);
  67478. }
  67479. }
  67480. // Particles Systems
  67481. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67482. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67483. var parsedParticleSystem = parsedData.particleSystems[index];
  67484. if (parsedParticleSystem.activeParticleCount) {
  67485. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67486. container.particleSystems.push(ps);
  67487. }
  67488. else {
  67489. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67490. container.particleSystems.push(ps);
  67491. }
  67492. }
  67493. }
  67494. // Lens flares
  67495. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67496. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67497. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67498. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67499. container.lensFlareSystems.push(lf);
  67500. }
  67501. }
  67502. // Shadows
  67503. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67504. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67505. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67506. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67507. container.shadowGenerators.push(sg);
  67508. }
  67509. }
  67510. // Lights exclusions / inclusions
  67511. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67512. var light_2 = scene.lights[index];
  67513. // Excluded check
  67514. if (light_2._excludedMeshesIds.length > 0) {
  67515. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67516. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67517. if (excludedMesh) {
  67518. light_2.excludedMeshes.push(excludedMesh);
  67519. }
  67520. }
  67521. light_2._excludedMeshesIds = [];
  67522. }
  67523. // Included check
  67524. if (light_2._includedOnlyMeshesIds.length > 0) {
  67525. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67526. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67527. if (includedOnlyMesh) {
  67528. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67529. }
  67530. }
  67531. light_2._includedOnlyMeshesIds = [];
  67532. }
  67533. }
  67534. // Effect layers
  67535. if (parsedData.effectLayers) {
  67536. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67537. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67538. container.effectLayers.push(effectLayer);
  67539. }
  67540. }
  67541. // Actions (scene)
  67542. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67543. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67544. }
  67545. if (!addToScene) {
  67546. container.removeAllFromScene();
  67547. }
  67548. }
  67549. catch (err) {
  67550. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67551. if (onError) {
  67552. onError(msg, err);
  67553. }
  67554. else {
  67555. BABYLON.Tools.Log(msg);
  67556. throw err;
  67557. }
  67558. }
  67559. finally {
  67560. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67561. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67562. }
  67563. }
  67564. return container;
  67565. };
  67566. BABYLON.SceneLoader.RegisterPlugin({
  67567. name: "babylon.js",
  67568. extensions: ".babylon",
  67569. canDirectLoad: function (data) {
  67570. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67571. return true;
  67572. }
  67573. return false;
  67574. },
  67575. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67576. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67577. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67578. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67579. // and avoid problems with multiple concurrent .babylon loads.
  67580. var log = "importMesh has failed JSON parse";
  67581. try {
  67582. var parsedData = JSON.parse(data);
  67583. log = "";
  67584. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67585. if (!meshesNames) {
  67586. meshesNames = null;
  67587. }
  67588. else if (!Array.isArray(meshesNames)) {
  67589. meshesNames = [meshesNames];
  67590. }
  67591. var hierarchyIds = new Array();
  67592. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67593. var loadedSkeletonsIds = [];
  67594. var loadedMaterialsIds = [];
  67595. var index;
  67596. var cache;
  67597. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67598. var parsedMesh = parsedData.meshes[index];
  67599. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67600. if (meshesNames !== null) {
  67601. // Remove found mesh name from list.
  67602. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67603. }
  67604. //Geometry?
  67605. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67606. //does the file contain geometries?
  67607. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67608. //find the correct geometry and add it to the scene
  67609. var found = false;
  67610. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67611. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67612. return;
  67613. }
  67614. else {
  67615. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67616. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67617. switch (geometryType) {
  67618. case "boxes":
  67619. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67620. break;
  67621. case "spheres":
  67622. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67623. break;
  67624. case "cylinders":
  67625. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67626. break;
  67627. case "toruses":
  67628. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67629. break;
  67630. case "grounds":
  67631. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67632. break;
  67633. case "planes":
  67634. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67635. break;
  67636. case "torusKnots":
  67637. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67638. break;
  67639. case "vertexData":
  67640. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67641. break;
  67642. }
  67643. found = true;
  67644. }
  67645. });
  67646. }
  67647. });
  67648. if (found === false) {
  67649. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67650. }
  67651. }
  67652. }
  67653. // Material ?
  67654. if (parsedMesh.materialId) {
  67655. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67656. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67657. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67658. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67659. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67660. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67661. var subMatId = parsedMultiMaterial.materials[matIndex];
  67662. loadedMaterialsIds.push(subMatId);
  67663. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67664. if (mat) {
  67665. log += "\n\tMaterial " + mat.toString(fullDetails);
  67666. }
  67667. }
  67668. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67669. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67670. if (mmat) {
  67671. materialFound = true;
  67672. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67673. }
  67674. break;
  67675. }
  67676. }
  67677. }
  67678. if (materialFound === false) {
  67679. loadedMaterialsIds.push(parsedMesh.materialId);
  67680. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67681. if (!mat) {
  67682. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67683. }
  67684. else {
  67685. log += "\n\tMaterial " + mat.toString(fullDetails);
  67686. }
  67687. }
  67688. }
  67689. // Skeleton ?
  67690. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67691. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67692. if (skeletonAlreadyLoaded === false) {
  67693. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67694. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67695. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67696. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67697. skeletons.push(skeleton);
  67698. loadedSkeletonsIds.push(parsedSkeleton.id);
  67699. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67700. }
  67701. }
  67702. }
  67703. }
  67704. // Morph targets ?
  67705. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67706. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67707. var managerData = _a[_i];
  67708. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67709. }
  67710. }
  67711. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67712. meshes.push(mesh);
  67713. log += "\n\tMesh " + mesh.toString(fullDetails);
  67714. }
  67715. }
  67716. // Connecting parents
  67717. var currentMesh;
  67718. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67719. currentMesh = scene.meshes[index];
  67720. if (currentMesh._waitingParentId) {
  67721. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67722. currentMesh._waitingParentId = null;
  67723. }
  67724. }
  67725. // freeze and compute world matrix application
  67726. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67727. currentMesh = scene.meshes[index];
  67728. if (currentMesh._waitingFreezeWorldMatrix) {
  67729. currentMesh.freezeWorldMatrix();
  67730. currentMesh._waitingFreezeWorldMatrix = null;
  67731. }
  67732. else {
  67733. currentMesh.computeWorldMatrix(true);
  67734. }
  67735. }
  67736. }
  67737. // Particles
  67738. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67739. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67740. var parsedParticleSystem = parsedData.particleSystems[index];
  67741. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67742. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67743. }
  67744. }
  67745. }
  67746. return true;
  67747. }
  67748. catch (err) {
  67749. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67750. if (onError) {
  67751. onError(msg, err);
  67752. }
  67753. else {
  67754. BABYLON.Tools.Log(msg);
  67755. throw err;
  67756. }
  67757. }
  67758. finally {
  67759. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67760. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67761. }
  67762. }
  67763. return false;
  67764. },
  67765. load: function (scene, data, rootUrl, onError) {
  67766. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67767. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67768. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67769. // and avoid problems with multiple concurrent .babylon loads.
  67770. var log = "importScene has failed JSON parse";
  67771. try {
  67772. var parsedData = JSON.parse(data);
  67773. log = "";
  67774. // Scene
  67775. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67776. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67777. }
  67778. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67779. scene.autoClear = parsedData.autoClear;
  67780. }
  67781. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67782. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67783. }
  67784. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67785. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67786. }
  67787. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67788. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67789. }
  67790. // Fog
  67791. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67792. scene.fogMode = parsedData.fogMode;
  67793. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67794. scene.fogStart = parsedData.fogStart;
  67795. scene.fogEnd = parsedData.fogEnd;
  67796. scene.fogDensity = parsedData.fogDensity;
  67797. log += "\tFog mode for scene: ";
  67798. switch (scene.fogMode) {
  67799. // getters not compiling, so using hardcoded
  67800. case 1:
  67801. log += "exp\n";
  67802. break;
  67803. case 2:
  67804. log += "exp2\n";
  67805. break;
  67806. case 3:
  67807. log += "linear\n";
  67808. break;
  67809. }
  67810. }
  67811. //Physics
  67812. if (parsedData.physicsEnabled) {
  67813. var physicsPlugin;
  67814. if (parsedData.physicsEngine === "cannon") {
  67815. physicsPlugin = new BABYLON.CannonJSPlugin();
  67816. }
  67817. else if (parsedData.physicsEngine === "oimo") {
  67818. physicsPlugin = new BABYLON.OimoJSPlugin();
  67819. }
  67820. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67821. //else - default engine, which is currently oimo
  67822. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67823. scene.enablePhysics(physicsGravity, physicsPlugin);
  67824. }
  67825. // Metadata
  67826. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67827. scene.metadata = parsedData.metadata;
  67828. }
  67829. //collisions, if defined. otherwise, default is true
  67830. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67831. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67832. }
  67833. scene.workerCollisions = !!parsedData.workerCollisions;
  67834. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67835. if (!container) {
  67836. return false;
  67837. }
  67838. if (parsedData.autoAnimate) {
  67839. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67840. }
  67841. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67842. scene.setActiveCameraByID(parsedData.activeCameraID);
  67843. }
  67844. // Environment texture
  67845. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67846. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67847. if (parsedData.createDefaultSkybox === true) {
  67848. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67849. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67850. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67851. }
  67852. }
  67853. // Finish
  67854. return true;
  67855. }
  67856. catch (err) {
  67857. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67858. if (onError) {
  67859. onError(msg, err);
  67860. }
  67861. else {
  67862. BABYLON.Tools.Log(msg);
  67863. throw err;
  67864. }
  67865. }
  67866. finally {
  67867. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67868. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67869. }
  67870. }
  67871. return false;
  67872. },
  67873. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67874. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67875. return container;
  67876. }
  67877. });
  67878. })(BABYLON || (BABYLON = {}));
  67879. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67880. var BABYLON;
  67881. (function (BABYLON) {
  67882. var FilesInput = /** @class */ (function () {
  67883. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67884. this.onProcessFileCallback = function () { return true; };
  67885. this._engine = engine;
  67886. this._currentScene = scene;
  67887. this._sceneLoadedCallback = sceneLoadedCallback;
  67888. this._progressCallback = progressCallback;
  67889. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67890. this._textureLoadingCallback = textureLoadingCallback;
  67891. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67892. this._onReloadCallback = onReloadCallback;
  67893. this._errorCallback = errorCallback;
  67894. }
  67895. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67896. var _this = this;
  67897. if (elementToMonitor) {
  67898. this._elementToMonitor = elementToMonitor;
  67899. this._dragEnterHandler = function (e) { _this.drag(e); };
  67900. this._dragOverHandler = function (e) { _this.drag(e); };
  67901. this._dropHandler = function (e) { _this.drop(e); };
  67902. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67903. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67904. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67905. }
  67906. };
  67907. FilesInput.prototype.dispose = function () {
  67908. if (!this._elementToMonitor) {
  67909. return;
  67910. }
  67911. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67912. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67913. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67914. };
  67915. FilesInput.prototype.renderFunction = function () {
  67916. if (this._additionalRenderLoopLogicCallback) {
  67917. this._additionalRenderLoopLogicCallback();
  67918. }
  67919. if (this._currentScene) {
  67920. if (this._textureLoadingCallback) {
  67921. var remaining = this._currentScene.getWaitingItemsCount();
  67922. if (remaining > 0) {
  67923. this._textureLoadingCallback(remaining);
  67924. }
  67925. }
  67926. this._currentScene.render();
  67927. }
  67928. };
  67929. FilesInput.prototype.drag = function (e) {
  67930. e.stopPropagation();
  67931. e.preventDefault();
  67932. };
  67933. FilesInput.prototype.drop = function (eventDrop) {
  67934. eventDrop.stopPropagation();
  67935. eventDrop.preventDefault();
  67936. this.loadFiles(eventDrop);
  67937. };
  67938. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67939. var _this = this;
  67940. var reader = folder.createReader();
  67941. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67942. reader.readEntries(function (entries) {
  67943. remaining.count += entries.length;
  67944. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67945. var entry = entries_1[_i];
  67946. if (entry.isFile) {
  67947. entry.file(function (file) {
  67948. file.correctName = relativePath + file.name;
  67949. files.push(file);
  67950. if (--remaining.count === 0) {
  67951. callback();
  67952. }
  67953. });
  67954. }
  67955. else if (entry.isDirectory) {
  67956. _this._traverseFolder(entry, files, remaining, callback);
  67957. }
  67958. }
  67959. if (--remaining.count) {
  67960. callback();
  67961. }
  67962. });
  67963. };
  67964. FilesInput.prototype._processFiles = function (files) {
  67965. for (var i = 0; i < files.length; i++) {
  67966. var name = files[i].correctName.toLowerCase();
  67967. var extension = name.split('.').pop();
  67968. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67969. continue;
  67970. }
  67971. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67972. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67973. this._sceneFileToLoad = files[i];
  67974. }
  67975. else {
  67976. FilesInput.FilesToLoad[name] = files[i];
  67977. }
  67978. }
  67979. };
  67980. FilesInput.prototype.loadFiles = function (event) {
  67981. var _this = this;
  67982. if (this._startingProcessingFilesCallback)
  67983. this._startingProcessingFilesCallback();
  67984. // Handling data transfer via drag'n'drop
  67985. if (event && event.dataTransfer && event.dataTransfer.files) {
  67986. this._filesToLoad = event.dataTransfer.files;
  67987. }
  67988. // Handling files from input files
  67989. if (event && event.target && event.target.files) {
  67990. this._filesToLoad = event.target.files;
  67991. }
  67992. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67993. var files_1 = new Array();
  67994. var folders = [];
  67995. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67996. for (var i = 0; i < this._filesToLoad.length; i++) {
  67997. var fileToLoad = this._filesToLoad[i];
  67998. var name_1 = fileToLoad.name.toLowerCase();
  67999. var entry = void 0;
  68000. fileToLoad.correctName = name_1;
  68001. if (items) {
  68002. var item = items[i];
  68003. if (item.getAsEntry) {
  68004. entry = item.getAsEntry();
  68005. }
  68006. else if (item.webkitGetAsEntry) {
  68007. entry = item.webkitGetAsEntry();
  68008. }
  68009. }
  68010. if (!entry) {
  68011. files_1.push(fileToLoad);
  68012. }
  68013. else {
  68014. if (entry.isDirectory) {
  68015. folders.push(entry);
  68016. }
  68017. else {
  68018. files_1.push(fileToLoad);
  68019. }
  68020. }
  68021. }
  68022. if (folders.length === 0) {
  68023. this._processFiles(files_1);
  68024. this._processReload();
  68025. }
  68026. else {
  68027. var remaining = { count: folders.length };
  68028. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68029. var folder = folders_1[_i];
  68030. this._traverseFolder(folder, files_1, remaining, function () {
  68031. _this._processFiles(files_1);
  68032. if (remaining.count === 0) {
  68033. _this._processReload();
  68034. }
  68035. });
  68036. }
  68037. }
  68038. }
  68039. };
  68040. FilesInput.prototype._processReload = function () {
  68041. if (this._onReloadCallback) {
  68042. this._onReloadCallback(this._sceneFileToLoad);
  68043. }
  68044. else {
  68045. this.reload();
  68046. }
  68047. };
  68048. FilesInput.prototype.reload = function () {
  68049. var _this = this;
  68050. // If a scene file has been provided
  68051. if (this._sceneFileToLoad) {
  68052. if (this._currentScene) {
  68053. if (BABYLON.Tools.errorsCount > 0) {
  68054. BABYLON.Tools.ClearLogCache();
  68055. }
  68056. this._engine.stopRenderLoop();
  68057. this._currentScene.dispose();
  68058. }
  68059. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68060. if (_this._progressCallback) {
  68061. _this._progressCallback(progress);
  68062. }
  68063. }).then(function (scene) {
  68064. _this._currentScene = scene;
  68065. if (_this._sceneLoadedCallback) {
  68066. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68067. }
  68068. // Wait for textures and shaders to be ready
  68069. _this._currentScene.executeWhenReady(function () {
  68070. _this._engine.runRenderLoop(function () {
  68071. _this.renderFunction();
  68072. });
  68073. });
  68074. }).catch(function (error) {
  68075. if (_this._errorCallback) {
  68076. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68077. }
  68078. });
  68079. }
  68080. else {
  68081. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68082. }
  68083. };
  68084. FilesInput.FilesToLoad = {};
  68085. return FilesInput;
  68086. }());
  68087. BABYLON.FilesInput = FilesInput;
  68088. })(BABYLON || (BABYLON = {}));
  68089. //# sourceMappingURL=babylon.filesInput.js.map
  68090. var BABYLON;
  68091. (function (BABYLON) {
  68092. /**
  68093. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68094. * The underlying implementation relies on an associative array to ensure the best performances.
  68095. * The value can be anything including 'null' but except 'undefined'
  68096. */
  68097. var StringDictionary = /** @class */ (function () {
  68098. function StringDictionary() {
  68099. this._count = 0;
  68100. this._data = {};
  68101. }
  68102. /**
  68103. * This will clear this dictionary and copy the content from the 'source' one.
  68104. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68105. * @param source the dictionary to take the content from and copy to this dictionary
  68106. */
  68107. StringDictionary.prototype.copyFrom = function (source) {
  68108. var _this = this;
  68109. this.clear();
  68110. source.forEach(function (t, v) { return _this.add(t, v); });
  68111. };
  68112. /**
  68113. * Get a value based from its key
  68114. * @param key the given key to get the matching value from
  68115. * @return the value if found, otherwise undefined is returned
  68116. */
  68117. StringDictionary.prototype.get = function (key) {
  68118. var val = this._data[key];
  68119. if (val !== undefined) {
  68120. return val;
  68121. }
  68122. return undefined;
  68123. };
  68124. /**
  68125. * Get a value from its key or add it if it doesn't exist.
  68126. * This method will ensure you that a given key/data will be present in the dictionary.
  68127. * @param key the given key to get the matching value from
  68128. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68129. * The factory will only be invoked if there's no data for the given key.
  68130. * @return the value corresponding to the key.
  68131. */
  68132. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68133. var val = this.get(key);
  68134. if (val !== undefined) {
  68135. return val;
  68136. }
  68137. val = factory(key);
  68138. if (val) {
  68139. this.add(key, val);
  68140. }
  68141. return val;
  68142. };
  68143. /**
  68144. * Get a value from its key if present in the dictionary otherwise add it
  68145. * @param key the key to get the value from
  68146. * @param val if there's no such key/value pair in the dictionary add it with this value
  68147. * @return the value corresponding to the key
  68148. */
  68149. StringDictionary.prototype.getOrAdd = function (key, val) {
  68150. var curVal = this.get(key);
  68151. if (curVal !== undefined) {
  68152. return curVal;
  68153. }
  68154. this.add(key, val);
  68155. return val;
  68156. };
  68157. /**
  68158. * Check if there's a given key in the dictionary
  68159. * @param key the key to check for
  68160. * @return true if the key is present, false otherwise
  68161. */
  68162. StringDictionary.prototype.contains = function (key) {
  68163. return this._data[key] !== undefined;
  68164. };
  68165. /**
  68166. * Add a new key and its corresponding value
  68167. * @param key the key to add
  68168. * @param value the value corresponding to the key
  68169. * @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
  68170. */
  68171. StringDictionary.prototype.add = function (key, value) {
  68172. if (this._data[key] !== undefined) {
  68173. return false;
  68174. }
  68175. this._data[key] = value;
  68176. ++this._count;
  68177. return true;
  68178. };
  68179. StringDictionary.prototype.set = function (key, value) {
  68180. if (this._data[key] === undefined) {
  68181. return false;
  68182. }
  68183. this._data[key] = value;
  68184. return true;
  68185. };
  68186. /**
  68187. * Get the element of the given key and remove it from the dictionary
  68188. * @param key
  68189. */
  68190. StringDictionary.prototype.getAndRemove = function (key) {
  68191. var val = this.get(key);
  68192. if (val !== undefined) {
  68193. delete this._data[key];
  68194. --this._count;
  68195. return val;
  68196. }
  68197. return null;
  68198. };
  68199. /**
  68200. * Remove a key/value from the dictionary.
  68201. * @param key the key to remove
  68202. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68203. */
  68204. StringDictionary.prototype.remove = function (key) {
  68205. if (this.contains(key)) {
  68206. delete this._data[key];
  68207. --this._count;
  68208. return true;
  68209. }
  68210. return false;
  68211. };
  68212. /**
  68213. * Clear the whole content of the dictionary
  68214. */
  68215. StringDictionary.prototype.clear = function () {
  68216. this._data = {};
  68217. this._count = 0;
  68218. };
  68219. Object.defineProperty(StringDictionary.prototype, "count", {
  68220. get: function () {
  68221. return this._count;
  68222. },
  68223. enumerable: true,
  68224. configurable: true
  68225. });
  68226. /**
  68227. * Execute a callback on each key/val of the dictionary.
  68228. * Note that you can remove any element in this dictionary in the callback implementation
  68229. * @param callback the callback to execute on a given key/value pair
  68230. */
  68231. StringDictionary.prototype.forEach = function (callback) {
  68232. for (var cur in this._data) {
  68233. var val = this._data[cur];
  68234. callback(cur, val);
  68235. }
  68236. };
  68237. /**
  68238. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68239. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68240. * Note that you can remove any element in this dictionary in the callback implementation
  68241. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68242. */
  68243. StringDictionary.prototype.first = function (callback) {
  68244. for (var cur in this._data) {
  68245. var val = this._data[cur];
  68246. var res = callback(cur, val);
  68247. if (res) {
  68248. return res;
  68249. }
  68250. }
  68251. return null;
  68252. };
  68253. return StringDictionary;
  68254. }());
  68255. BABYLON.StringDictionary = StringDictionary;
  68256. })(BABYLON || (BABYLON = {}));
  68257. //# sourceMappingURL=babylon.stringDictionary.js.map
  68258. var BABYLON;
  68259. (function (BABYLON) {
  68260. var Tags = /** @class */ (function () {
  68261. function Tags() {
  68262. }
  68263. Tags.EnableFor = function (obj) {
  68264. obj._tags = obj._tags || {};
  68265. obj.hasTags = function () {
  68266. return Tags.HasTags(obj);
  68267. };
  68268. obj.addTags = function (tagsString) {
  68269. return Tags.AddTagsTo(obj, tagsString);
  68270. };
  68271. obj.removeTags = function (tagsString) {
  68272. return Tags.RemoveTagsFrom(obj, tagsString);
  68273. };
  68274. obj.matchesTagsQuery = function (tagsQuery) {
  68275. return Tags.MatchesQuery(obj, tagsQuery);
  68276. };
  68277. };
  68278. Tags.DisableFor = function (obj) {
  68279. delete obj._tags;
  68280. delete obj.hasTags;
  68281. delete obj.addTags;
  68282. delete obj.removeTags;
  68283. delete obj.matchesTagsQuery;
  68284. };
  68285. Tags.HasTags = function (obj) {
  68286. if (!obj._tags) {
  68287. return false;
  68288. }
  68289. return !BABYLON.Tools.IsEmpty(obj._tags);
  68290. };
  68291. Tags.GetTags = function (obj, asString) {
  68292. if (asString === void 0) { asString = true; }
  68293. if (!obj._tags) {
  68294. return null;
  68295. }
  68296. if (asString) {
  68297. var tagsArray = [];
  68298. for (var tag in obj._tags) {
  68299. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68300. tagsArray.push(tag);
  68301. }
  68302. }
  68303. return tagsArray.join(" ");
  68304. }
  68305. else {
  68306. return obj._tags;
  68307. }
  68308. };
  68309. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68310. // a tag cannot start with '||', '&&', and '!'
  68311. // it cannot contain whitespaces
  68312. Tags.AddTagsTo = function (obj, tagsString) {
  68313. if (!tagsString) {
  68314. return;
  68315. }
  68316. if (typeof tagsString !== "string") {
  68317. return;
  68318. }
  68319. var tags = tagsString.split(" ");
  68320. tags.forEach(function (tag, index, array) {
  68321. Tags._AddTagTo(obj, tag);
  68322. });
  68323. };
  68324. Tags._AddTagTo = function (obj, tag) {
  68325. tag = tag.trim();
  68326. if (tag === "" || tag === "true" || tag === "false") {
  68327. return;
  68328. }
  68329. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68330. return;
  68331. }
  68332. Tags.EnableFor(obj);
  68333. obj._tags[tag] = true;
  68334. };
  68335. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68336. if (!Tags.HasTags(obj)) {
  68337. return;
  68338. }
  68339. var tags = tagsString.split(" ");
  68340. for (var t in tags) {
  68341. Tags._RemoveTagFrom(obj, tags[t]);
  68342. }
  68343. };
  68344. Tags._RemoveTagFrom = function (obj, tag) {
  68345. delete obj._tags[tag];
  68346. };
  68347. Tags.MatchesQuery = function (obj, tagsQuery) {
  68348. if (tagsQuery === undefined) {
  68349. return true;
  68350. }
  68351. if (tagsQuery === "") {
  68352. return Tags.HasTags(obj);
  68353. }
  68354. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68355. };
  68356. return Tags;
  68357. }());
  68358. BABYLON.Tags = Tags;
  68359. })(BABYLON || (BABYLON = {}));
  68360. //# sourceMappingURL=babylon.tags.js.map
  68361. var BABYLON;
  68362. (function (BABYLON) {
  68363. /**
  68364. * Class used to evalaute queries containing `and` and `or` operators
  68365. */
  68366. var AndOrNotEvaluator = /** @class */ (function () {
  68367. function AndOrNotEvaluator() {
  68368. }
  68369. /**
  68370. * Evaluate a query
  68371. * @param query defines the query to evaluate
  68372. * @param evaluateCallback defines the callback used to filter result
  68373. * @returns true if the query matches
  68374. */
  68375. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68376. if (!query.match(/\([^\(\)]*\)/g)) {
  68377. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68378. }
  68379. else {
  68380. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68381. // remove parenthesis
  68382. r = r.slice(1, r.length - 1);
  68383. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68384. });
  68385. }
  68386. if (query === "true") {
  68387. return true;
  68388. }
  68389. if (query === "false") {
  68390. return false;
  68391. }
  68392. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68393. };
  68394. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68395. evaluateCallback = evaluateCallback || (function (r) {
  68396. return r === "true" ? true : false;
  68397. });
  68398. var result;
  68399. var or = parenthesisContent.split("||");
  68400. for (var i in or) {
  68401. if (or.hasOwnProperty(i)) {
  68402. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68403. var and = ori.split("&&");
  68404. if (and.length > 1) {
  68405. for (var j = 0; j < and.length; ++j) {
  68406. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68407. if (andj !== "true" && andj !== "false") {
  68408. if (andj[0] === "!") {
  68409. result = !evaluateCallback(andj.substring(1));
  68410. }
  68411. else {
  68412. result = evaluateCallback(andj);
  68413. }
  68414. }
  68415. else {
  68416. result = andj === "true" ? true : false;
  68417. }
  68418. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68419. ori = "false";
  68420. break;
  68421. }
  68422. }
  68423. }
  68424. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68425. result = true;
  68426. break;
  68427. }
  68428. // result equals false (or undefined)
  68429. if (ori !== "true" && ori !== "false") {
  68430. if (ori[0] === "!") {
  68431. result = !evaluateCallback(ori.substring(1));
  68432. }
  68433. else {
  68434. result = evaluateCallback(ori);
  68435. }
  68436. }
  68437. else {
  68438. result = ori === "true" ? true : false;
  68439. }
  68440. }
  68441. }
  68442. // the whole parenthesis scope is replaced by 'true' or 'false'
  68443. return result ? "true" : "false";
  68444. };
  68445. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68446. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68447. // remove whitespaces
  68448. r = r.replace(/[\s]/g, function () { return ""; });
  68449. return r.length % 2 ? "!" : "";
  68450. });
  68451. booleanString = booleanString.trim();
  68452. if (booleanString === "!true") {
  68453. booleanString = "false";
  68454. }
  68455. else if (booleanString === "!false") {
  68456. booleanString = "true";
  68457. }
  68458. return booleanString;
  68459. };
  68460. return AndOrNotEvaluator;
  68461. }());
  68462. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68463. })(BABYLON || (BABYLON = {}));
  68464. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68465. var BABYLON;
  68466. (function (BABYLON) {
  68467. /**
  68468. * Class used to enable access to IndexedDB
  68469. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68470. */
  68471. var Database = /** @class */ (function () {
  68472. /**
  68473. * Creates a new Database
  68474. * @param urlToScene defines the url to load the scene
  68475. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68476. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68477. */
  68478. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68479. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68480. var _this = this;
  68481. // Handling various flavors of prefixed version of IndexedDB
  68482. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68483. this.callbackManifestChecked = callbackManifestChecked;
  68484. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68485. this.db = null;
  68486. this._enableSceneOffline = false;
  68487. this._enableTexturesOffline = false;
  68488. this.manifestVersionFound = 0;
  68489. this.mustUpdateRessources = false;
  68490. this.hasReachedQuota = false;
  68491. if (!Database.IDBStorageEnabled) {
  68492. this.callbackManifestChecked(true);
  68493. }
  68494. else {
  68495. if (disableManifestCheck) {
  68496. this._enableSceneOffline = true;
  68497. this._enableTexturesOffline = true;
  68498. this.manifestVersionFound = 1;
  68499. BABYLON.Tools.SetImmediate(function () {
  68500. _this.callbackManifestChecked(true);
  68501. });
  68502. }
  68503. else {
  68504. this._checkManifestFile();
  68505. }
  68506. }
  68507. }
  68508. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68509. /**
  68510. * Gets a boolean indicating if scene must be saved in the database
  68511. */
  68512. get: function () {
  68513. return this._enableSceneOffline;
  68514. },
  68515. enumerable: true,
  68516. configurable: true
  68517. });
  68518. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68519. /**
  68520. * Gets a boolean indicating if textures must be saved in the database
  68521. */
  68522. get: function () {
  68523. return this._enableTexturesOffline;
  68524. },
  68525. enumerable: true,
  68526. configurable: true
  68527. });
  68528. Database.prototype._checkManifestFile = function () {
  68529. var _this = this;
  68530. var noManifestFile = function () {
  68531. _this._enableSceneOffline = false;
  68532. _this._enableTexturesOffline = false;
  68533. _this.callbackManifestChecked(false);
  68534. };
  68535. var timeStampUsed = false;
  68536. var manifestURL = this.currentSceneUrl + ".manifest";
  68537. var xhr = new XMLHttpRequest();
  68538. if (navigator.onLine) {
  68539. // Adding a timestamp to by-pass browsers' cache
  68540. timeStampUsed = true;
  68541. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68542. }
  68543. xhr.open("GET", manifestURL, true);
  68544. xhr.addEventListener("load", function () {
  68545. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68546. try {
  68547. var manifestFile = JSON.parse(xhr.response);
  68548. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68549. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68550. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68551. _this.manifestVersionFound = manifestFile.version;
  68552. }
  68553. if (_this.callbackManifestChecked) {
  68554. _this.callbackManifestChecked(true);
  68555. }
  68556. }
  68557. catch (ex) {
  68558. noManifestFile();
  68559. }
  68560. }
  68561. else {
  68562. noManifestFile();
  68563. }
  68564. }, false);
  68565. xhr.addEventListener("error", function (event) {
  68566. if (timeStampUsed) {
  68567. timeStampUsed = false;
  68568. // Let's retry without the timeStamp
  68569. // It could fail when coupled with HTML5 Offline API
  68570. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68571. xhr.open("GET", retryManifestURL, true);
  68572. xhr.send();
  68573. }
  68574. else {
  68575. noManifestFile();
  68576. }
  68577. }, false);
  68578. try {
  68579. xhr.send();
  68580. }
  68581. catch (ex) {
  68582. BABYLON.Tools.Error("Error on XHR send request.");
  68583. this.callbackManifestChecked(false);
  68584. }
  68585. };
  68586. /**
  68587. * Open the database and make it available
  68588. * @param successCallback defines the callback to call on success
  68589. * @param errorCallback defines the callback to call on error
  68590. */
  68591. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68592. var _this = this;
  68593. var handleError = function () {
  68594. _this.isSupported = false;
  68595. if (errorCallback)
  68596. errorCallback();
  68597. };
  68598. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68599. // Your browser doesn't support IndexedDB
  68600. this.isSupported = false;
  68601. if (errorCallback)
  68602. errorCallback();
  68603. }
  68604. else {
  68605. // If the DB hasn't been opened or created yet
  68606. if (!this.db) {
  68607. this.hasReachedQuota = false;
  68608. this.isSupported = true;
  68609. var request = this.idbFactory.open("babylonjs", 1);
  68610. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68611. request.onerror = function (event) {
  68612. handleError();
  68613. };
  68614. // executes when a version change transaction cannot complete due to other active transactions
  68615. request.onblocked = function (event) {
  68616. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68617. handleError();
  68618. };
  68619. // DB has been opened successfully
  68620. request.onsuccess = function (event) {
  68621. _this.db = request.result;
  68622. successCallback();
  68623. };
  68624. // Initialization of the DB. Creating Scenes & Textures stores
  68625. request.onupgradeneeded = function (event) {
  68626. _this.db = (event.target).result;
  68627. if (_this.db) {
  68628. try {
  68629. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68630. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68631. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68632. }
  68633. catch (ex) {
  68634. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68635. handleError();
  68636. }
  68637. }
  68638. };
  68639. }
  68640. // DB has already been created and opened
  68641. else {
  68642. if (successCallback)
  68643. successCallback();
  68644. }
  68645. }
  68646. };
  68647. /**
  68648. * Loads an image from the database
  68649. * @param url defines the url to load from
  68650. * @param image defines the target DOM image
  68651. */
  68652. Database.prototype.loadImageFromDB = function (url, image) {
  68653. var _this = this;
  68654. var completeURL = Database._ReturnFullUrlLocation(url);
  68655. var saveAndLoadImage = function () {
  68656. if (!_this.hasReachedQuota && _this.db !== null) {
  68657. // the texture is not yet in the DB, let's try to save it
  68658. _this._saveImageIntoDBAsync(completeURL, image);
  68659. }
  68660. // If the texture is not in the DB and we've reached the DB quota limit
  68661. // let's load it directly from the web
  68662. else {
  68663. image.src = url;
  68664. }
  68665. };
  68666. if (!this.mustUpdateRessources) {
  68667. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68668. }
  68669. // First time we're download the images or update requested in the manifest file by a version change
  68670. else {
  68671. saveAndLoadImage();
  68672. }
  68673. };
  68674. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68675. if (this.isSupported && this.db !== null) {
  68676. var texture;
  68677. var transaction = this.db.transaction(["textures"]);
  68678. transaction.onabort = function (event) {
  68679. image.src = url;
  68680. };
  68681. transaction.oncomplete = function (event) {
  68682. var blobTextureURL;
  68683. if (texture) {
  68684. var URL = window.URL || window.webkitURL;
  68685. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68686. image.onerror = function () {
  68687. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68688. image.src = url;
  68689. };
  68690. image.src = blobTextureURL;
  68691. }
  68692. else {
  68693. notInDBCallback();
  68694. }
  68695. };
  68696. var getRequest = transaction.objectStore("textures").get(url);
  68697. getRequest.onsuccess = function (event) {
  68698. texture = (event.target).result;
  68699. };
  68700. getRequest.onerror = function (event) {
  68701. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68702. image.src = url;
  68703. };
  68704. }
  68705. else {
  68706. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68707. image.src = url;
  68708. }
  68709. };
  68710. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68711. var _this = this;
  68712. if (this.isSupported) {
  68713. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68714. var generateBlobUrl = function () {
  68715. var blobTextureURL;
  68716. if (blob) {
  68717. var URL = window.URL || window.webkitURL;
  68718. try {
  68719. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68720. }
  68721. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68722. catch (ex) {
  68723. blobTextureURL = URL.createObjectURL(blob);
  68724. }
  68725. }
  68726. if (blobTextureURL) {
  68727. image.src = blobTextureURL;
  68728. }
  68729. };
  68730. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68731. var xhr = new XMLHttpRequest(), blob;
  68732. xhr.open("GET", url, true);
  68733. xhr.responseType = "blob";
  68734. xhr.addEventListener("load", function () {
  68735. if (xhr.status === 200 && _this.db) {
  68736. // Blob as response (XHR2)
  68737. blob = xhr.response;
  68738. var transaction = _this.db.transaction(["textures"], "readwrite");
  68739. // the transaction could abort because of a QuotaExceededError error
  68740. transaction.onabort = function (event) {
  68741. try {
  68742. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68743. var srcElement = (event.srcElement || event.target);
  68744. var error = srcElement.error;
  68745. if (error && error.name === "QuotaExceededError") {
  68746. _this.hasReachedQuota = true;
  68747. }
  68748. }
  68749. catch (ex) { }
  68750. generateBlobUrl();
  68751. };
  68752. transaction.oncomplete = function (event) {
  68753. generateBlobUrl();
  68754. };
  68755. var newTexture = { textureUrl: url, data: blob };
  68756. try {
  68757. // Put the blob into the dabase
  68758. var addRequest = transaction.objectStore("textures").put(newTexture);
  68759. addRequest.onsuccess = function (event) {
  68760. };
  68761. addRequest.onerror = function (event) {
  68762. generateBlobUrl();
  68763. };
  68764. }
  68765. catch (ex) {
  68766. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68767. if (ex.code === 25) {
  68768. Database.IsUASupportingBlobStorage = false;
  68769. }
  68770. image.src = url;
  68771. }
  68772. }
  68773. else {
  68774. image.src = url;
  68775. }
  68776. }, false);
  68777. xhr.addEventListener("error", function (event) {
  68778. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68779. image.src = url;
  68780. }, false);
  68781. xhr.send();
  68782. }
  68783. else {
  68784. image.src = url;
  68785. }
  68786. }
  68787. else {
  68788. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68789. image.src = url;
  68790. }
  68791. };
  68792. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68793. var _this = this;
  68794. var updateVersion = function () {
  68795. // the version is not yet in the DB or we need to update it
  68796. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68797. };
  68798. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68799. };
  68800. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68801. var _this = this;
  68802. if (this.isSupported && this.db) {
  68803. var version;
  68804. try {
  68805. var transaction = this.db.transaction(["versions"]);
  68806. transaction.oncomplete = function (event) {
  68807. if (version) {
  68808. // If the version in the JSON file is > than the version in DB
  68809. if (_this.manifestVersionFound > version.data) {
  68810. _this.mustUpdateRessources = true;
  68811. updateInDBCallback();
  68812. }
  68813. else {
  68814. callback(version.data);
  68815. }
  68816. }
  68817. // version was not found in DB
  68818. else {
  68819. _this.mustUpdateRessources = true;
  68820. updateInDBCallback();
  68821. }
  68822. };
  68823. transaction.onabort = function (event) {
  68824. callback(-1);
  68825. };
  68826. var getRequest = transaction.objectStore("versions").get(url);
  68827. getRequest.onsuccess = function (event) {
  68828. version = (event.target).result;
  68829. };
  68830. getRequest.onerror = function (event) {
  68831. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68832. callback(-1);
  68833. };
  68834. }
  68835. catch (ex) {
  68836. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68837. callback(-1);
  68838. }
  68839. }
  68840. else {
  68841. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68842. callback(-1);
  68843. }
  68844. };
  68845. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68846. var _this = this;
  68847. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68848. try {
  68849. // Open a transaction to the database
  68850. var transaction = this.db.transaction(["versions"], "readwrite");
  68851. // the transaction could abort because of a QuotaExceededError error
  68852. transaction.onabort = function (event) {
  68853. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68854. var error = event.srcElement['error'];
  68855. if (error && error.name === "QuotaExceededError") {
  68856. _this.hasReachedQuota = true;
  68857. }
  68858. }
  68859. catch (ex) { }
  68860. callback(-1);
  68861. };
  68862. transaction.oncomplete = function (event) {
  68863. callback(_this.manifestVersionFound);
  68864. };
  68865. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68866. // Put the scene into the database
  68867. var addRequest = transaction.objectStore("versions").put(newVersion);
  68868. addRequest.onsuccess = function (event) {
  68869. };
  68870. addRequest.onerror = function (event) {
  68871. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68872. };
  68873. }
  68874. catch (ex) {
  68875. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68876. callback(-1);
  68877. }
  68878. }
  68879. else {
  68880. callback(-1);
  68881. }
  68882. };
  68883. /**
  68884. * Loads a file from database
  68885. * @param url defines the URL to load from
  68886. * @param sceneLoaded defines a callback to call on success
  68887. * @param progressCallBack defines a callback to call when progress changed
  68888. * @param errorCallback defines a callback to call on error
  68889. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68890. */
  68891. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68892. var _this = this;
  68893. var completeUrl = Database._ReturnFullUrlLocation(url);
  68894. var saveAndLoadFile = function () {
  68895. // the scene is not yet in the DB, let's try to save it
  68896. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68897. };
  68898. this._checkVersionFromDB(completeUrl, function (version) {
  68899. if (version !== -1) {
  68900. if (!_this.mustUpdateRessources) {
  68901. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68902. }
  68903. else {
  68904. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68905. }
  68906. }
  68907. else {
  68908. if (errorCallback) {
  68909. errorCallback();
  68910. }
  68911. }
  68912. });
  68913. };
  68914. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68915. if (this.isSupported && this.db) {
  68916. var targetStore;
  68917. if (url.indexOf(".babylon") !== -1) {
  68918. targetStore = "scenes";
  68919. }
  68920. else {
  68921. targetStore = "textures";
  68922. }
  68923. var file;
  68924. var transaction = this.db.transaction([targetStore]);
  68925. transaction.oncomplete = function (event) {
  68926. if (file) {
  68927. callback(file.data);
  68928. }
  68929. // file was not found in DB
  68930. else {
  68931. notInDBCallback();
  68932. }
  68933. };
  68934. transaction.onabort = function (event) {
  68935. notInDBCallback();
  68936. };
  68937. var getRequest = transaction.objectStore(targetStore).get(url);
  68938. getRequest.onsuccess = function (event) {
  68939. file = (event.target).result;
  68940. };
  68941. getRequest.onerror = function (event) {
  68942. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68943. notInDBCallback();
  68944. };
  68945. }
  68946. else {
  68947. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68948. callback();
  68949. }
  68950. };
  68951. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68952. var _this = this;
  68953. if (this.isSupported) {
  68954. var targetStore;
  68955. if (url.indexOf(".babylon") !== -1) {
  68956. targetStore = "scenes";
  68957. }
  68958. else {
  68959. targetStore = "textures";
  68960. }
  68961. // Create XHR
  68962. var xhr = new XMLHttpRequest();
  68963. var fileData;
  68964. xhr.open("GET", url, true);
  68965. if (useArrayBuffer) {
  68966. xhr.responseType = "arraybuffer";
  68967. }
  68968. if (progressCallback) {
  68969. xhr.onprogress = progressCallback;
  68970. }
  68971. xhr.addEventListener("load", function () {
  68972. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68973. // Blob as response (XHR2)
  68974. //fileData = xhr.responseText;
  68975. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68976. if (!_this.hasReachedQuota && _this.db) {
  68977. // Open a transaction to the database
  68978. var transaction = _this.db.transaction([targetStore], "readwrite");
  68979. // the transaction could abort because of a QuotaExceededError error
  68980. transaction.onabort = function (event) {
  68981. try {
  68982. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68983. var error = event.srcElement['error'];
  68984. if (error && error.name === "QuotaExceededError") {
  68985. _this.hasReachedQuota = true;
  68986. }
  68987. }
  68988. catch (ex) { }
  68989. callback(fileData);
  68990. };
  68991. transaction.oncomplete = function (event) {
  68992. callback(fileData);
  68993. };
  68994. var newFile;
  68995. if (targetStore === "scenes") {
  68996. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68997. }
  68998. else {
  68999. newFile = { textureUrl: url, data: fileData };
  69000. }
  69001. try {
  69002. // Put the scene into the database
  69003. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69004. addRequest.onsuccess = function (event) {
  69005. };
  69006. addRequest.onerror = function (event) {
  69007. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69008. };
  69009. }
  69010. catch (ex) {
  69011. callback(fileData);
  69012. }
  69013. }
  69014. else {
  69015. callback(fileData);
  69016. }
  69017. }
  69018. else {
  69019. callback();
  69020. }
  69021. }, false);
  69022. xhr.addEventListener("error", function (event) {
  69023. BABYLON.Tools.Error("error on XHR request.");
  69024. callback();
  69025. }, false);
  69026. xhr.send();
  69027. }
  69028. else {
  69029. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69030. callback();
  69031. }
  69032. };
  69033. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69034. Database.IsUASupportingBlobStorage = true;
  69035. /** Gets a boolean indicating if Database storate is enabled */
  69036. Database.IDBStorageEnabled = true;
  69037. Database._ParseURL = function (url) {
  69038. var a = document.createElement('a');
  69039. a.href = url;
  69040. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69041. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69042. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69043. return absLocation;
  69044. };
  69045. Database._ReturnFullUrlLocation = function (url) {
  69046. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69047. return (Database._ParseURL(window.location.href) + url);
  69048. }
  69049. else {
  69050. return url;
  69051. }
  69052. };
  69053. return Database;
  69054. }());
  69055. BABYLON.Database = Database;
  69056. })(BABYLON || (BABYLON = {}));
  69057. //# sourceMappingURL=babylon.database.js.map
  69058. var BABYLON;
  69059. (function (BABYLON) {
  69060. var FresnelParameters = /** @class */ (function () {
  69061. function FresnelParameters() {
  69062. this._isEnabled = true;
  69063. this.leftColor = BABYLON.Color3.White();
  69064. this.rightColor = BABYLON.Color3.Black();
  69065. this.bias = 0;
  69066. this.power = 1;
  69067. }
  69068. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69069. get: function () {
  69070. return this._isEnabled;
  69071. },
  69072. set: function (value) {
  69073. if (this._isEnabled === value) {
  69074. return;
  69075. }
  69076. this._isEnabled = value;
  69077. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69078. },
  69079. enumerable: true,
  69080. configurable: true
  69081. });
  69082. FresnelParameters.prototype.clone = function () {
  69083. var newFresnelParameters = new FresnelParameters();
  69084. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69085. return newFresnelParameters;
  69086. };
  69087. FresnelParameters.prototype.serialize = function () {
  69088. var serializationObject = {};
  69089. serializationObject.isEnabled = this.isEnabled;
  69090. serializationObject.leftColor = this.leftColor.asArray();
  69091. serializationObject.rightColor = this.rightColor.asArray();
  69092. serializationObject.bias = this.bias;
  69093. serializationObject.power = this.power;
  69094. return serializationObject;
  69095. };
  69096. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69097. var fresnelParameters = new FresnelParameters();
  69098. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69099. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69100. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69101. fresnelParameters.bias = parsedFresnelParameters.bias;
  69102. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69103. return fresnelParameters;
  69104. };
  69105. return FresnelParameters;
  69106. }());
  69107. BABYLON.FresnelParameters = FresnelParameters;
  69108. })(BABYLON || (BABYLON = {}));
  69109. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69110. var BABYLON;
  69111. (function (BABYLON) {
  69112. var MultiMaterial = /** @class */ (function (_super) {
  69113. __extends(MultiMaterial, _super);
  69114. function MultiMaterial(name, scene) {
  69115. var _this = _super.call(this, name, scene, true) || this;
  69116. scene.multiMaterials.push(_this);
  69117. _this.subMaterials = new Array();
  69118. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69119. return _this;
  69120. }
  69121. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69122. get: function () {
  69123. return this._subMaterials;
  69124. },
  69125. set: function (value) {
  69126. this._subMaterials = value;
  69127. this._hookArray(value);
  69128. },
  69129. enumerable: true,
  69130. configurable: true
  69131. });
  69132. MultiMaterial.prototype._hookArray = function (array) {
  69133. var _this = this;
  69134. var oldPush = array.push;
  69135. array.push = function () {
  69136. var items = [];
  69137. for (var _i = 0; _i < arguments.length; _i++) {
  69138. items[_i] = arguments[_i];
  69139. }
  69140. var result = oldPush.apply(array, items);
  69141. _this._markAllSubMeshesAsTexturesDirty();
  69142. return result;
  69143. };
  69144. var oldSplice = array.splice;
  69145. array.splice = function (index, deleteCount) {
  69146. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69147. _this._markAllSubMeshesAsTexturesDirty();
  69148. return deleted;
  69149. };
  69150. };
  69151. // Properties
  69152. MultiMaterial.prototype.getSubMaterial = function (index) {
  69153. if (index < 0 || index >= this.subMaterials.length) {
  69154. return this.getScene().defaultMaterial;
  69155. }
  69156. return this.subMaterials[index];
  69157. };
  69158. MultiMaterial.prototype.getActiveTextures = function () {
  69159. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69160. if (subMaterial) {
  69161. return subMaterial.getActiveTextures();
  69162. }
  69163. else {
  69164. return [];
  69165. }
  69166. }));
  69167. var _a;
  69168. };
  69169. // Methods
  69170. MultiMaterial.prototype.getClassName = function () {
  69171. return "MultiMaterial";
  69172. };
  69173. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69174. for (var index = 0; index < this.subMaterials.length; index++) {
  69175. var subMaterial = this.subMaterials[index];
  69176. if (subMaterial) {
  69177. if (subMaterial.storeEffectOnSubMeshes) {
  69178. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69179. return false;
  69180. }
  69181. continue;
  69182. }
  69183. if (!subMaterial.isReady(mesh)) {
  69184. return false;
  69185. }
  69186. }
  69187. }
  69188. return true;
  69189. };
  69190. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69191. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69192. for (var index = 0; index < this.subMaterials.length; index++) {
  69193. var subMaterial = null;
  69194. var current = this.subMaterials[index];
  69195. if (cloneChildren && current) {
  69196. subMaterial = current.clone(name + "-" + current.name);
  69197. }
  69198. else {
  69199. subMaterial = this.subMaterials[index];
  69200. }
  69201. newMultiMaterial.subMaterials.push(subMaterial);
  69202. }
  69203. return newMultiMaterial;
  69204. };
  69205. MultiMaterial.prototype.serialize = function () {
  69206. var serializationObject = {};
  69207. serializationObject.name = this.name;
  69208. serializationObject.id = this.id;
  69209. if (BABYLON.Tags) {
  69210. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69211. }
  69212. serializationObject.materials = [];
  69213. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69214. var subMat = this.subMaterials[matIndex];
  69215. if (subMat) {
  69216. serializationObject.materials.push(subMat.id);
  69217. }
  69218. else {
  69219. serializationObject.materials.push(null);
  69220. }
  69221. }
  69222. return serializationObject;
  69223. };
  69224. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69225. var scene = this.getScene();
  69226. if (!scene) {
  69227. return;
  69228. }
  69229. var index = scene.multiMaterials.indexOf(this);
  69230. if (index >= 0) {
  69231. scene.multiMaterials.splice(index, 1);
  69232. }
  69233. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69234. };
  69235. return MultiMaterial;
  69236. }(BABYLON.Material));
  69237. BABYLON.MultiMaterial = MultiMaterial;
  69238. })(BABYLON || (BABYLON = {}));
  69239. //# sourceMappingURL=babylon.multiMaterial.js.map
  69240. var BABYLON;
  69241. (function (BABYLON) {
  69242. var FreeCameraTouchInput = /** @class */ (function () {
  69243. function FreeCameraTouchInput() {
  69244. this._offsetX = null;
  69245. this._offsetY = null;
  69246. this._pointerPressed = new Array();
  69247. this.touchAngularSensibility = 200000.0;
  69248. this.touchMoveSensibility = 250.0;
  69249. }
  69250. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69251. var _this = this;
  69252. var previousPosition = null;
  69253. if (this._pointerInput === undefined) {
  69254. this._onLostFocus = function (evt) {
  69255. _this._offsetX = null;
  69256. _this._offsetY = null;
  69257. };
  69258. this._pointerInput = function (p, s) {
  69259. var evt = p.event;
  69260. if (evt.pointerType === "mouse") {
  69261. return;
  69262. }
  69263. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69264. if (!noPreventDefault) {
  69265. evt.preventDefault();
  69266. }
  69267. _this._pointerPressed.push(evt.pointerId);
  69268. if (_this._pointerPressed.length !== 1) {
  69269. return;
  69270. }
  69271. previousPosition = {
  69272. x: evt.clientX,
  69273. y: evt.clientY
  69274. };
  69275. }
  69276. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69277. if (!noPreventDefault) {
  69278. evt.preventDefault();
  69279. }
  69280. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69281. if (index === -1) {
  69282. return;
  69283. }
  69284. _this._pointerPressed.splice(index, 1);
  69285. if (index != 0) {
  69286. return;
  69287. }
  69288. previousPosition = null;
  69289. _this._offsetX = null;
  69290. _this._offsetY = null;
  69291. }
  69292. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69293. if (!noPreventDefault) {
  69294. evt.preventDefault();
  69295. }
  69296. if (!previousPosition) {
  69297. return;
  69298. }
  69299. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69300. if (index != 0) {
  69301. return;
  69302. }
  69303. _this._offsetX = evt.clientX - previousPosition.x;
  69304. _this._offsetY = -(evt.clientY - previousPosition.y);
  69305. }
  69306. };
  69307. }
  69308. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69309. if (this._onLostFocus) {
  69310. element.addEventListener("blur", this._onLostFocus);
  69311. }
  69312. };
  69313. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69314. if (this._pointerInput && element) {
  69315. if (this._observer) {
  69316. this.camera.getScene().onPointerObservable.remove(this._observer);
  69317. this._observer = null;
  69318. }
  69319. if (this._onLostFocus) {
  69320. element.removeEventListener("blur", this._onLostFocus);
  69321. this._onLostFocus = null;
  69322. }
  69323. this._pointerPressed = [];
  69324. this._offsetX = null;
  69325. this._offsetY = null;
  69326. }
  69327. };
  69328. FreeCameraTouchInput.prototype.checkInputs = function () {
  69329. if (this._offsetX && this._offsetY) {
  69330. var camera = this.camera;
  69331. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69332. if (this._pointerPressed.length > 1) {
  69333. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69334. }
  69335. else {
  69336. var speed = camera._computeLocalCameraSpeed();
  69337. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69338. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69339. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69340. }
  69341. }
  69342. };
  69343. FreeCameraTouchInput.prototype.getClassName = function () {
  69344. return "FreeCameraTouchInput";
  69345. };
  69346. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69347. return "touch";
  69348. };
  69349. __decorate([
  69350. BABYLON.serialize()
  69351. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69352. __decorate([
  69353. BABYLON.serialize()
  69354. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69355. return FreeCameraTouchInput;
  69356. }());
  69357. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69358. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69359. })(BABYLON || (BABYLON = {}));
  69360. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69361. var BABYLON;
  69362. (function (BABYLON) {
  69363. // We're mainly based on the logic defined into the FreeCamera code
  69364. var TouchCamera = /** @class */ (function (_super) {
  69365. __extends(TouchCamera, _super);
  69366. //-- end properties for backward compatibility for inputs
  69367. function TouchCamera(name, position, scene) {
  69368. var _this = _super.call(this, name, position, scene) || this;
  69369. _this.inputs.addTouch();
  69370. _this._setupInputs();
  69371. return _this;
  69372. }
  69373. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69374. //-- Begin properties for backward compatibility for inputs
  69375. get: function () {
  69376. var touch = this.inputs.attached["touch"];
  69377. if (touch)
  69378. return touch.touchAngularSensibility;
  69379. return 0;
  69380. },
  69381. set: function (value) {
  69382. var touch = this.inputs.attached["touch"];
  69383. if (touch)
  69384. touch.touchAngularSensibility = value;
  69385. },
  69386. enumerable: true,
  69387. configurable: true
  69388. });
  69389. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69390. get: function () {
  69391. var touch = this.inputs.attached["touch"];
  69392. if (touch)
  69393. return touch.touchMoveSensibility;
  69394. return 0;
  69395. },
  69396. set: function (value) {
  69397. var touch = this.inputs.attached["touch"];
  69398. if (touch)
  69399. touch.touchMoveSensibility = value;
  69400. },
  69401. enumerable: true,
  69402. configurable: true
  69403. });
  69404. TouchCamera.prototype.getClassName = function () {
  69405. return "TouchCamera";
  69406. };
  69407. TouchCamera.prototype._setupInputs = function () {
  69408. var mouse = this.inputs.attached["mouse"];
  69409. if (mouse) {
  69410. mouse.touchEnabled = false;
  69411. }
  69412. };
  69413. return TouchCamera;
  69414. }(BABYLON.FreeCamera));
  69415. BABYLON.TouchCamera = TouchCamera;
  69416. })(BABYLON || (BABYLON = {}));
  69417. //# sourceMappingURL=babylon.touchCamera.js.map
  69418. var BABYLON;
  69419. (function (BABYLON) {
  69420. var ProceduralTexture = /** @class */ (function (_super) {
  69421. __extends(ProceduralTexture, _super);
  69422. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69423. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69424. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69425. if (isCube === void 0) { isCube = false; }
  69426. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69427. _this.isCube = isCube;
  69428. _this.isEnabled = true;
  69429. _this._currentRefreshId = -1;
  69430. _this._refreshRate = 1;
  69431. _this._vertexBuffers = {};
  69432. _this._uniforms = new Array();
  69433. _this._samplers = new Array();
  69434. _this._textures = {};
  69435. _this._floats = {};
  69436. _this._floatsArrays = {};
  69437. _this._colors3 = {};
  69438. _this._colors4 = {};
  69439. _this._vectors2 = {};
  69440. _this._vectors3 = {};
  69441. _this._matrices = {};
  69442. _this._fallbackTextureUsed = false;
  69443. scene.proceduralTextures.push(_this);
  69444. _this._engine = scene.getEngine();
  69445. _this.name = name;
  69446. _this.isRenderTarget = true;
  69447. _this._size = size;
  69448. _this._generateMipMaps = generateMipMaps;
  69449. _this.setFragment(fragment);
  69450. _this._fallbackTexture = fallbackTexture;
  69451. if (isCube) {
  69452. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69453. _this.setFloat("face", 0);
  69454. }
  69455. else {
  69456. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69457. }
  69458. // VBO
  69459. var vertices = [];
  69460. vertices.push(1, 1);
  69461. vertices.push(-1, 1);
  69462. vertices.push(-1, -1);
  69463. vertices.push(1, -1);
  69464. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69465. _this._createIndexBuffer();
  69466. return _this;
  69467. }
  69468. ProceduralTexture.prototype._createIndexBuffer = function () {
  69469. var engine = this._engine;
  69470. // Indices
  69471. var indices = [];
  69472. indices.push(0);
  69473. indices.push(1);
  69474. indices.push(2);
  69475. indices.push(0);
  69476. indices.push(2);
  69477. indices.push(3);
  69478. this._indexBuffer = engine.createIndexBuffer(indices);
  69479. };
  69480. ProceduralTexture.prototype._rebuild = function () {
  69481. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69482. if (vb) {
  69483. vb._rebuild();
  69484. }
  69485. this._createIndexBuffer();
  69486. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69487. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69488. }
  69489. };
  69490. ProceduralTexture.prototype.reset = function () {
  69491. if (this._effect === undefined) {
  69492. return;
  69493. }
  69494. var engine = this._engine;
  69495. engine._releaseEffect(this._effect);
  69496. };
  69497. ProceduralTexture.prototype.isReady = function () {
  69498. var _this = this;
  69499. var engine = this._engine;
  69500. var shaders;
  69501. if (!this._fragment) {
  69502. return false;
  69503. }
  69504. if (this._fallbackTextureUsed) {
  69505. return true;
  69506. }
  69507. if (this._fragment.fragmentElement !== undefined) {
  69508. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69509. }
  69510. else {
  69511. shaders = { vertex: "procedural", fragment: this._fragment };
  69512. }
  69513. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69514. _this.releaseInternalTexture();
  69515. if (_this._fallbackTexture) {
  69516. _this._texture = _this._fallbackTexture._texture;
  69517. if (_this._texture) {
  69518. _this._texture.incrementReferences();
  69519. }
  69520. }
  69521. _this._fallbackTextureUsed = true;
  69522. });
  69523. return this._effect.isReady();
  69524. };
  69525. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69526. this._currentRefreshId = -1;
  69527. };
  69528. ProceduralTexture.prototype.setFragment = function (fragment) {
  69529. this._fragment = fragment;
  69530. };
  69531. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69532. get: function () {
  69533. return this._refreshRate;
  69534. },
  69535. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69536. set: function (value) {
  69537. this._refreshRate = value;
  69538. this.resetRefreshCounter();
  69539. },
  69540. enumerable: true,
  69541. configurable: true
  69542. });
  69543. ProceduralTexture.prototype._shouldRender = function () {
  69544. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69545. return false;
  69546. }
  69547. if (this._fallbackTextureUsed) {
  69548. return false;
  69549. }
  69550. if (this._currentRefreshId === -1) { // At least render once
  69551. this._currentRefreshId = 1;
  69552. return true;
  69553. }
  69554. if (this.refreshRate === this._currentRefreshId) {
  69555. this._currentRefreshId = 1;
  69556. return true;
  69557. }
  69558. this._currentRefreshId++;
  69559. return false;
  69560. };
  69561. ProceduralTexture.prototype.getRenderSize = function () {
  69562. return this._size;
  69563. };
  69564. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69565. if (this._fallbackTextureUsed) {
  69566. return;
  69567. }
  69568. this.releaseInternalTexture();
  69569. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69570. };
  69571. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69572. if (this._uniforms.indexOf(uniformName) === -1) {
  69573. this._uniforms.push(uniformName);
  69574. }
  69575. };
  69576. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69577. if (this._samplers.indexOf(name) === -1) {
  69578. this._samplers.push(name);
  69579. }
  69580. this._textures[name] = texture;
  69581. return this;
  69582. };
  69583. ProceduralTexture.prototype.setFloat = function (name, value) {
  69584. this._checkUniform(name);
  69585. this._floats[name] = value;
  69586. return this;
  69587. };
  69588. ProceduralTexture.prototype.setFloats = function (name, value) {
  69589. this._checkUniform(name);
  69590. this._floatsArrays[name] = value;
  69591. return this;
  69592. };
  69593. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69594. this._checkUniform(name);
  69595. this._colors3[name] = value;
  69596. return this;
  69597. };
  69598. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69599. this._checkUniform(name);
  69600. this._colors4[name] = value;
  69601. return this;
  69602. };
  69603. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69604. this._checkUniform(name);
  69605. this._vectors2[name] = value;
  69606. return this;
  69607. };
  69608. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69609. this._checkUniform(name);
  69610. this._vectors3[name] = value;
  69611. return this;
  69612. };
  69613. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69614. this._checkUniform(name);
  69615. this._matrices[name] = value;
  69616. return this;
  69617. };
  69618. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69619. var scene = this.getScene();
  69620. if (!scene) {
  69621. return;
  69622. }
  69623. var engine = this._engine;
  69624. // Render
  69625. engine.enableEffect(this._effect);
  69626. engine.setState(false);
  69627. // Texture
  69628. for (var name in this._textures) {
  69629. this._effect.setTexture(name, this._textures[name]);
  69630. }
  69631. // Float
  69632. for (name in this._floats) {
  69633. this._effect.setFloat(name, this._floats[name]);
  69634. }
  69635. // Floats
  69636. for (name in this._floatsArrays) {
  69637. this._effect.setArray(name, this._floatsArrays[name]);
  69638. }
  69639. // Color3
  69640. for (name in this._colors3) {
  69641. this._effect.setColor3(name, this._colors3[name]);
  69642. }
  69643. // Color4
  69644. for (name in this._colors4) {
  69645. var color = this._colors4[name];
  69646. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69647. }
  69648. // Vector2
  69649. for (name in this._vectors2) {
  69650. this._effect.setVector2(name, this._vectors2[name]);
  69651. }
  69652. // Vector3
  69653. for (name in this._vectors3) {
  69654. this._effect.setVector3(name, this._vectors3[name]);
  69655. }
  69656. // Matrix
  69657. for (name in this._matrices) {
  69658. this._effect.setMatrix(name, this._matrices[name]);
  69659. }
  69660. if (!this._texture) {
  69661. return;
  69662. }
  69663. if (this.isCube) {
  69664. for (var face = 0; face < 6; face++) {
  69665. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69666. // VBOs
  69667. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69668. this._effect.setFloat("face", face);
  69669. // Clear
  69670. engine.clear(scene.clearColor, true, true, true);
  69671. // Draw order
  69672. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69673. // Mipmaps
  69674. if (face === 5) {
  69675. engine.generateMipMapsForCubemap(this._texture);
  69676. }
  69677. }
  69678. }
  69679. else {
  69680. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69681. // VBOs
  69682. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69683. // Clear
  69684. engine.clear(scene.clearColor, true, true, true);
  69685. // Draw order
  69686. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69687. }
  69688. // Unbind
  69689. engine.unBindFramebuffer(this._texture, this.isCube);
  69690. if (this.onGenerated) {
  69691. this.onGenerated();
  69692. }
  69693. };
  69694. ProceduralTexture.prototype.clone = function () {
  69695. var textureSize = this.getSize();
  69696. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69697. // Base texture
  69698. newTexture.hasAlpha = this.hasAlpha;
  69699. newTexture.level = this.level;
  69700. // RenderTarget Texture
  69701. newTexture.coordinatesMode = this.coordinatesMode;
  69702. return newTexture;
  69703. };
  69704. ProceduralTexture.prototype.dispose = function () {
  69705. var scene = this.getScene();
  69706. if (!scene) {
  69707. return;
  69708. }
  69709. var index = scene.proceduralTextures.indexOf(this);
  69710. if (index >= 0) {
  69711. scene.proceduralTextures.splice(index, 1);
  69712. }
  69713. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69714. if (vertexBuffer) {
  69715. vertexBuffer.dispose();
  69716. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69717. }
  69718. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69719. this._indexBuffer = null;
  69720. }
  69721. _super.prototype.dispose.call(this);
  69722. };
  69723. return ProceduralTexture;
  69724. }(BABYLON.Texture));
  69725. BABYLON.ProceduralTexture = ProceduralTexture;
  69726. })(BABYLON || (BABYLON = {}));
  69727. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69728. var BABYLON;
  69729. (function (BABYLON) {
  69730. var CustomProceduralTexture = /** @class */ (function (_super) {
  69731. __extends(CustomProceduralTexture, _super);
  69732. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69733. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69734. _this._animate = true;
  69735. _this._time = 0;
  69736. _this._texturePath = texturePath;
  69737. //Try to load json
  69738. _this.loadJson(texturePath);
  69739. _this.refreshRate = 1;
  69740. return _this;
  69741. }
  69742. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69743. var _this = this;
  69744. var noConfigFile = function () {
  69745. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69746. try {
  69747. _this.setFragment(_this._texturePath);
  69748. }
  69749. catch (ex) {
  69750. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69751. }
  69752. };
  69753. var configFileUrl = jsonUrl + "/config.json";
  69754. var xhr = new XMLHttpRequest();
  69755. xhr.open("GET", configFileUrl, true);
  69756. xhr.addEventListener("load", function () {
  69757. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69758. try {
  69759. _this._config = JSON.parse(xhr.response);
  69760. _this.updateShaderUniforms();
  69761. _this.updateTextures();
  69762. _this.setFragment(_this._texturePath + "/custom");
  69763. _this._animate = _this._config.animate;
  69764. _this.refreshRate = _this._config.refreshrate;
  69765. }
  69766. catch (ex) {
  69767. noConfigFile();
  69768. }
  69769. }
  69770. else {
  69771. noConfigFile();
  69772. }
  69773. }, false);
  69774. xhr.addEventListener("error", function () {
  69775. noConfigFile();
  69776. }, false);
  69777. try {
  69778. xhr.send();
  69779. }
  69780. catch (ex) {
  69781. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69782. }
  69783. };
  69784. CustomProceduralTexture.prototype.isReady = function () {
  69785. if (!_super.prototype.isReady.call(this)) {
  69786. return false;
  69787. }
  69788. for (var name in this._textures) {
  69789. var texture = this._textures[name];
  69790. if (!texture.isReady()) {
  69791. return false;
  69792. }
  69793. }
  69794. return true;
  69795. };
  69796. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69797. var scene = this.getScene();
  69798. if (this._animate && scene) {
  69799. this._time += scene.getAnimationRatio() * 0.03;
  69800. this.updateShaderUniforms();
  69801. }
  69802. _super.prototype.render.call(this, useCameraPostProcess);
  69803. };
  69804. CustomProceduralTexture.prototype.updateTextures = function () {
  69805. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69806. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69807. }
  69808. };
  69809. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69810. if (this._config) {
  69811. for (var j = 0; j < this._config.uniforms.length; j++) {
  69812. var uniform = this._config.uniforms[j];
  69813. switch (uniform.type) {
  69814. case "float":
  69815. this.setFloat(uniform.name, uniform.value);
  69816. break;
  69817. case "color3":
  69818. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69819. break;
  69820. case "color4":
  69821. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69822. break;
  69823. case "vector2":
  69824. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69825. break;
  69826. case "vector3":
  69827. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69828. break;
  69829. }
  69830. }
  69831. }
  69832. this.setFloat("time", this._time);
  69833. };
  69834. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69835. get: function () {
  69836. return this._animate;
  69837. },
  69838. set: function (value) {
  69839. this._animate = value;
  69840. },
  69841. enumerable: true,
  69842. configurable: true
  69843. });
  69844. return CustomProceduralTexture;
  69845. }(BABYLON.ProceduralTexture));
  69846. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69847. })(BABYLON || (BABYLON = {}));
  69848. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69849. var BABYLON;
  69850. (function (BABYLON) {
  69851. var FreeCameraGamepadInput = /** @class */ (function () {
  69852. function FreeCameraGamepadInput() {
  69853. this.gamepadAngularSensibility = 200;
  69854. this.gamepadMoveSensibility = 40;
  69855. // private members
  69856. this._cameraTransform = BABYLON.Matrix.Identity();
  69857. this._deltaTransform = BABYLON.Vector3.Zero();
  69858. this._vector3 = BABYLON.Vector3.Zero();
  69859. this._vector2 = BABYLON.Vector2.Zero();
  69860. }
  69861. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69862. var _this = this;
  69863. var manager = this.camera.getScene().gamepadManager;
  69864. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69865. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69866. // prioritize XBOX gamepads.
  69867. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69868. _this.gamepad = gamepad;
  69869. }
  69870. }
  69871. });
  69872. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69873. if (_this.gamepad === gamepad) {
  69874. _this.gamepad = null;
  69875. }
  69876. });
  69877. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69878. };
  69879. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69880. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69881. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69882. this.gamepad = null;
  69883. };
  69884. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69885. if (this.gamepad && this.gamepad.leftStick) {
  69886. var camera = this.camera;
  69887. var LSValues = this.gamepad.leftStick;
  69888. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69889. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69890. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69891. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69892. var RSValues = this.gamepad.rightStick;
  69893. if (RSValues) {
  69894. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69895. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69896. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69897. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69898. }
  69899. else {
  69900. RSValues = { x: 0, y: 0 };
  69901. }
  69902. if (!camera.rotationQuaternion) {
  69903. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69904. }
  69905. else {
  69906. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69907. }
  69908. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69909. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69910. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69911. camera.cameraDirection.addInPlace(this._deltaTransform);
  69912. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69913. camera.cameraRotation.addInPlace(this._vector2);
  69914. }
  69915. };
  69916. FreeCameraGamepadInput.prototype.getClassName = function () {
  69917. return "FreeCameraGamepadInput";
  69918. };
  69919. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69920. return "gamepad";
  69921. };
  69922. __decorate([
  69923. BABYLON.serialize()
  69924. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69925. __decorate([
  69926. BABYLON.serialize()
  69927. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69928. return FreeCameraGamepadInput;
  69929. }());
  69930. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69931. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69932. })(BABYLON || (BABYLON = {}));
  69933. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69934. var BABYLON;
  69935. (function (BABYLON) {
  69936. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69937. function ArcRotateCameraGamepadInput() {
  69938. this.gamepadRotationSensibility = 80;
  69939. this.gamepadMoveSensibility = 40;
  69940. }
  69941. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69942. var _this = this;
  69943. var manager = this.camera.getScene().gamepadManager;
  69944. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69945. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69946. // prioritize XBOX gamepads.
  69947. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69948. _this.gamepad = gamepad;
  69949. }
  69950. }
  69951. });
  69952. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69953. if (_this.gamepad === gamepad) {
  69954. _this.gamepad = null;
  69955. }
  69956. });
  69957. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69958. };
  69959. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69960. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69961. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69962. this.gamepad = null;
  69963. };
  69964. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69965. if (this.gamepad) {
  69966. var camera = this.camera;
  69967. var RSValues = this.gamepad.rightStick;
  69968. if (RSValues) {
  69969. if (RSValues.x != 0) {
  69970. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69971. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69972. camera.inertialAlphaOffset += normalizedRX;
  69973. }
  69974. }
  69975. if (RSValues.y != 0) {
  69976. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69977. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69978. camera.inertialBetaOffset += normalizedRY;
  69979. }
  69980. }
  69981. }
  69982. var LSValues = this.gamepad.leftStick;
  69983. if (LSValues && LSValues.y != 0) {
  69984. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69985. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69986. this.camera.inertialRadiusOffset -= normalizedLY;
  69987. }
  69988. }
  69989. }
  69990. };
  69991. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69992. return "ArcRotateCameraGamepadInput";
  69993. };
  69994. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69995. return "gamepad";
  69996. };
  69997. __decorate([
  69998. BABYLON.serialize()
  69999. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70000. __decorate([
  70001. BABYLON.serialize()
  70002. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70003. return ArcRotateCameraGamepadInput;
  70004. }());
  70005. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70006. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70007. })(BABYLON || (BABYLON = {}));
  70008. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70009. var BABYLON;
  70010. (function (BABYLON) {
  70011. var GamepadManager = /** @class */ (function () {
  70012. function GamepadManager(_scene) {
  70013. var _this = this;
  70014. this._scene = _scene;
  70015. this._babylonGamepads = [];
  70016. this._oneGamepadConnected = false;
  70017. this._isMonitoring = false;
  70018. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70019. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70020. this._gamepadEventSupported = false;
  70021. }
  70022. else {
  70023. this._gamepadEventSupported = 'GamepadEvent' in window;
  70024. this._gamepadSupport = (navigator.getGamepads ||
  70025. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70026. }
  70027. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70028. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70029. for (var i in _this._babylonGamepads) {
  70030. var gamepad = _this._babylonGamepads[i];
  70031. if (gamepad && gamepad._isConnected) {
  70032. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70033. }
  70034. }
  70035. });
  70036. this._onGamepadConnectedEvent = function (evt) {
  70037. var gamepad = evt.gamepad;
  70038. if (gamepad.index in _this._babylonGamepads) {
  70039. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70040. return;
  70041. }
  70042. }
  70043. var newGamepad;
  70044. if (_this._babylonGamepads[gamepad.index]) {
  70045. newGamepad = _this._babylonGamepads[gamepad.index];
  70046. newGamepad.browserGamepad = gamepad;
  70047. newGamepad._isConnected = true;
  70048. }
  70049. else {
  70050. newGamepad = _this._addNewGamepad(gamepad);
  70051. }
  70052. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70053. _this._startMonitoringGamepads();
  70054. };
  70055. this._onGamepadDisconnectedEvent = function (evt) {
  70056. var gamepad = evt.gamepad;
  70057. // Remove the gamepad from the list of gamepads to monitor.
  70058. for (var i in _this._babylonGamepads) {
  70059. if (_this._babylonGamepads[i].index === gamepad.index) {
  70060. var disconnectedGamepad = _this._babylonGamepads[i];
  70061. disconnectedGamepad._isConnected = false;
  70062. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70063. break;
  70064. }
  70065. }
  70066. };
  70067. if (this._gamepadSupport) {
  70068. //first add already-connected gamepads
  70069. this._updateGamepadObjects();
  70070. if (this._babylonGamepads.length) {
  70071. this._startMonitoringGamepads();
  70072. }
  70073. // Checking if the gamepad connected event is supported (like in Firefox)
  70074. if (this._gamepadEventSupported) {
  70075. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70076. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70077. }
  70078. else {
  70079. this._startMonitoringGamepads();
  70080. }
  70081. }
  70082. }
  70083. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70084. get: function () {
  70085. return this._babylonGamepads;
  70086. },
  70087. enumerable: true,
  70088. configurable: true
  70089. });
  70090. GamepadManager.prototype.getGamepadByType = function (type) {
  70091. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70092. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70093. var gamepad = _a[_i];
  70094. if (gamepad && gamepad.type === type) {
  70095. return gamepad;
  70096. }
  70097. }
  70098. return null;
  70099. };
  70100. GamepadManager.prototype.dispose = function () {
  70101. if (this._gamepadEventSupported) {
  70102. if (this._onGamepadConnectedEvent) {
  70103. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70104. }
  70105. if (this._onGamepadDisconnectedEvent) {
  70106. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70107. }
  70108. this._onGamepadConnectedEvent = null;
  70109. this._onGamepadDisconnectedEvent = null;
  70110. }
  70111. this._babylonGamepads.forEach(function (gamepad) {
  70112. gamepad.dispose();
  70113. });
  70114. this.onGamepadConnectedObservable.clear();
  70115. this.onGamepadDisconnectedObservable.clear();
  70116. this._oneGamepadConnected = false;
  70117. this._stopMonitoringGamepads();
  70118. this._babylonGamepads = [];
  70119. };
  70120. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70121. if (!this._oneGamepadConnected) {
  70122. this._oneGamepadConnected = true;
  70123. }
  70124. var newGamepad;
  70125. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70126. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70127. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70128. }
  70129. // if pose is supported, use the (WebVR) pose enabled controller
  70130. else if (gamepad.pose) {
  70131. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70132. }
  70133. else {
  70134. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70135. }
  70136. this._babylonGamepads[newGamepad.index] = newGamepad;
  70137. return newGamepad;
  70138. };
  70139. GamepadManager.prototype._startMonitoringGamepads = function () {
  70140. if (!this._isMonitoring) {
  70141. this._isMonitoring = true;
  70142. //back-comp
  70143. if (!this._scene) {
  70144. this._checkGamepadsStatus();
  70145. }
  70146. }
  70147. };
  70148. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70149. this._isMonitoring = false;
  70150. };
  70151. GamepadManager.prototype._checkGamepadsStatus = function () {
  70152. var _this = this;
  70153. // Hack to be compatible Chrome
  70154. this._updateGamepadObjects();
  70155. for (var i in this._babylonGamepads) {
  70156. var gamepad = this._babylonGamepads[i];
  70157. if (!gamepad || !gamepad.isConnected) {
  70158. continue;
  70159. }
  70160. gamepad.update();
  70161. }
  70162. if (this._isMonitoring && !this._scene) {
  70163. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70164. }
  70165. };
  70166. // This function is called only on Chrome, which does not properly support
  70167. // connection/disconnection events and forces you to recopy again the gamepad object
  70168. GamepadManager.prototype._updateGamepadObjects = function () {
  70169. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70170. for (var i = 0; i < gamepads.length; i++) {
  70171. var gamepad = gamepads[i];
  70172. if (gamepad) {
  70173. if (!this._babylonGamepads[gamepad.index]) {
  70174. var newGamepad = this._addNewGamepad(gamepad);
  70175. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70176. }
  70177. else {
  70178. // Forced to copy again this object for Chrome for unknown reason
  70179. this._babylonGamepads[i].browserGamepad = gamepad;
  70180. if (!this._babylonGamepads[i].isConnected) {
  70181. this._babylonGamepads[i]._isConnected = true;
  70182. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70183. }
  70184. }
  70185. }
  70186. }
  70187. };
  70188. return GamepadManager;
  70189. }());
  70190. BABYLON.GamepadManager = GamepadManager;
  70191. })(BABYLON || (BABYLON = {}));
  70192. //# sourceMappingURL=babylon.gamepadManager.js.map
  70193. var BABYLON;
  70194. (function (BABYLON) {
  70195. var StickValues = /** @class */ (function () {
  70196. function StickValues(x, y) {
  70197. this.x = x;
  70198. this.y = y;
  70199. }
  70200. return StickValues;
  70201. }());
  70202. BABYLON.StickValues = StickValues;
  70203. var Gamepad = /** @class */ (function () {
  70204. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70205. if (leftStickX === void 0) { leftStickX = 0; }
  70206. if (leftStickY === void 0) { leftStickY = 1; }
  70207. if (rightStickX === void 0) { rightStickX = 2; }
  70208. if (rightStickY === void 0) { rightStickY = 3; }
  70209. this.id = id;
  70210. this.index = index;
  70211. this.browserGamepad = browserGamepad;
  70212. this._isConnected = true;
  70213. this._invertLeftStickY = false;
  70214. this.type = Gamepad.GAMEPAD;
  70215. this._leftStickAxisX = leftStickX;
  70216. this._leftStickAxisY = leftStickY;
  70217. this._rightStickAxisX = rightStickX;
  70218. this._rightStickAxisY = rightStickY;
  70219. if (this.browserGamepad.axes.length >= 2) {
  70220. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70221. }
  70222. if (this.browserGamepad.axes.length >= 4) {
  70223. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70224. }
  70225. }
  70226. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70227. get: function () {
  70228. return this._isConnected;
  70229. },
  70230. enumerable: true,
  70231. configurable: true
  70232. });
  70233. Gamepad.prototype.onleftstickchanged = function (callback) {
  70234. this._onleftstickchanged = callback;
  70235. };
  70236. Gamepad.prototype.onrightstickchanged = function (callback) {
  70237. this._onrightstickchanged = callback;
  70238. };
  70239. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70240. get: function () {
  70241. return this._leftStick;
  70242. },
  70243. set: function (newValues) {
  70244. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70245. this._onleftstickchanged(newValues);
  70246. }
  70247. this._leftStick = newValues;
  70248. },
  70249. enumerable: true,
  70250. configurable: true
  70251. });
  70252. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70253. get: function () {
  70254. return this._rightStick;
  70255. },
  70256. set: function (newValues) {
  70257. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70258. this._onrightstickchanged(newValues);
  70259. }
  70260. this._rightStick = newValues;
  70261. },
  70262. enumerable: true,
  70263. configurable: true
  70264. });
  70265. Gamepad.prototype.update = function () {
  70266. if (this._leftStick) {
  70267. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70268. if (this._invertLeftStickY) {
  70269. this.leftStick.y *= -1;
  70270. }
  70271. }
  70272. if (this._rightStick) {
  70273. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70274. }
  70275. };
  70276. Gamepad.prototype.dispose = function () {
  70277. };
  70278. Gamepad.GAMEPAD = 0;
  70279. Gamepad.GENERIC = 1;
  70280. Gamepad.XBOX = 2;
  70281. Gamepad.POSE_ENABLED = 3;
  70282. return Gamepad;
  70283. }());
  70284. BABYLON.Gamepad = Gamepad;
  70285. var GenericPad = /** @class */ (function (_super) {
  70286. __extends(GenericPad, _super);
  70287. function GenericPad(id, index, browserGamepad) {
  70288. var _this = _super.call(this, id, index, browserGamepad) || this;
  70289. _this.onButtonDownObservable = new BABYLON.Observable();
  70290. _this.onButtonUpObservable = new BABYLON.Observable();
  70291. _this.type = Gamepad.GENERIC;
  70292. _this._buttons = new Array(browserGamepad.buttons.length);
  70293. return _this;
  70294. }
  70295. GenericPad.prototype.onbuttondown = function (callback) {
  70296. this._onbuttondown = callback;
  70297. };
  70298. GenericPad.prototype.onbuttonup = function (callback) {
  70299. this._onbuttonup = callback;
  70300. };
  70301. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70302. if (newValue !== currentValue) {
  70303. if (newValue === 1) {
  70304. if (this._onbuttondown) {
  70305. this._onbuttondown(buttonIndex);
  70306. }
  70307. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70308. }
  70309. if (newValue === 0) {
  70310. if (this._onbuttonup) {
  70311. this._onbuttonup(buttonIndex);
  70312. }
  70313. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70314. }
  70315. }
  70316. return newValue;
  70317. };
  70318. GenericPad.prototype.update = function () {
  70319. _super.prototype.update.call(this);
  70320. for (var index = 0; index < this._buttons.length; index++) {
  70321. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70322. }
  70323. };
  70324. GenericPad.prototype.dispose = function () {
  70325. _super.prototype.dispose.call(this);
  70326. this.onButtonDownObservable.clear();
  70327. this.onButtonUpObservable.clear();
  70328. };
  70329. return GenericPad;
  70330. }(Gamepad));
  70331. BABYLON.GenericPad = GenericPad;
  70332. })(BABYLON || (BABYLON = {}));
  70333. //# sourceMappingURL=babylon.gamepad.js.map
  70334. var BABYLON;
  70335. (function (BABYLON) {
  70336. /**
  70337. * Defines supported buttons for XBox360 compatible gamepads
  70338. */
  70339. var Xbox360Button;
  70340. (function (Xbox360Button) {
  70341. /** A */
  70342. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70343. /** B */
  70344. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70345. /** X */
  70346. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70347. /** Y */
  70348. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70349. /** Start */
  70350. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70351. /** Back */
  70352. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70353. /** Left button */
  70354. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70355. /** Right button */
  70356. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70357. /** Left stick */
  70358. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70359. /** Right stick */
  70360. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70361. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70362. /** Defines values for XBox360 DPad */
  70363. var Xbox360Dpad;
  70364. (function (Xbox360Dpad) {
  70365. /** Up */
  70366. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70367. /** Down */
  70368. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70369. /** Left */
  70370. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70371. /** Right */
  70372. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70373. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70374. /**
  70375. * Defines a XBox360 gamepad
  70376. */
  70377. var Xbox360Pad = /** @class */ (function (_super) {
  70378. __extends(Xbox360Pad, _super);
  70379. /**
  70380. * Creates a new XBox360 gamepad object
  70381. * @param id defines the id of this gamepad
  70382. * @param index defines its index
  70383. * @param gamepad defines the internal HTML gamepad object
  70384. * @param xboxOne defines if it is a XBox One gamepad
  70385. */
  70386. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70387. if (xboxOne === void 0) { xboxOne = false; }
  70388. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70389. _this._leftTrigger = 0;
  70390. _this._rightTrigger = 0;
  70391. /** Observable raised when a button is pressed */
  70392. _this.onButtonDownObservable = new BABYLON.Observable();
  70393. /** Observable raised when a button is released */
  70394. _this.onButtonUpObservable = new BABYLON.Observable();
  70395. /** Observable raised when a pad is pressed */
  70396. _this.onPadDownObservable = new BABYLON.Observable();
  70397. /** Observable raised when a pad is released */
  70398. _this.onPadUpObservable = new BABYLON.Observable();
  70399. _this._buttonA = 0;
  70400. _this._buttonB = 0;
  70401. _this._buttonX = 0;
  70402. _this._buttonY = 0;
  70403. _this._buttonBack = 0;
  70404. _this._buttonStart = 0;
  70405. _this._buttonLB = 0;
  70406. _this._buttonRB = 0;
  70407. _this._buttonLeftStick = 0;
  70408. _this._buttonRightStick = 0;
  70409. _this._dPadUp = 0;
  70410. _this._dPadDown = 0;
  70411. _this._dPadLeft = 0;
  70412. _this._dPadRight = 0;
  70413. _this._isXboxOnePad = false;
  70414. _this.type = BABYLON.Gamepad.XBOX;
  70415. _this._isXboxOnePad = xboxOne;
  70416. return _this;
  70417. }
  70418. /**
  70419. * Defines the callback to call when left trigger is pressed
  70420. * @param callback defines the callback to use
  70421. */
  70422. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70423. this._onlefttriggerchanged = callback;
  70424. };
  70425. /**
  70426. * Defines the callback to call when right trigger is pressed
  70427. * @param callback defines the callback to use
  70428. */
  70429. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70430. this._onrighttriggerchanged = callback;
  70431. };
  70432. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70433. /**
  70434. * Gets or sets left trigger value
  70435. */
  70436. get: function () {
  70437. return this._leftTrigger;
  70438. },
  70439. set: function (newValue) {
  70440. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70441. this._onlefttriggerchanged(newValue);
  70442. }
  70443. this._leftTrigger = newValue;
  70444. },
  70445. enumerable: true,
  70446. configurable: true
  70447. });
  70448. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70449. /**
  70450. * Gets or sets right trigger value
  70451. */
  70452. get: function () {
  70453. return this._rightTrigger;
  70454. },
  70455. set: function (newValue) {
  70456. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70457. this._onrighttriggerchanged(newValue);
  70458. }
  70459. this._rightTrigger = newValue;
  70460. },
  70461. enumerable: true,
  70462. configurable: true
  70463. });
  70464. /**
  70465. * Defines the callback to call when a button is pressed
  70466. * @param callback defines the callback to use
  70467. */
  70468. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70469. this._onbuttondown = callback;
  70470. };
  70471. /**
  70472. * Defines the callback to call when a button is released
  70473. * @param callback defines the callback to use
  70474. */
  70475. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70476. this._onbuttonup = callback;
  70477. };
  70478. /**
  70479. * Defines the callback to call when a pad is pressed
  70480. * @param callback defines the callback to use
  70481. */
  70482. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70483. this._ondpaddown = callback;
  70484. };
  70485. /**
  70486. * Defines the callback to call when a pad is released
  70487. * @param callback defines the callback to use
  70488. */
  70489. Xbox360Pad.prototype.ondpadup = function (callback) {
  70490. this._ondpadup = callback;
  70491. };
  70492. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70493. if (newValue !== currentValue) {
  70494. if (newValue === 1) {
  70495. if (this._onbuttondown) {
  70496. this._onbuttondown(buttonType);
  70497. }
  70498. this.onButtonDownObservable.notifyObservers(buttonType);
  70499. }
  70500. if (newValue === 0) {
  70501. if (this._onbuttonup) {
  70502. this._onbuttonup(buttonType);
  70503. }
  70504. this.onButtonUpObservable.notifyObservers(buttonType);
  70505. }
  70506. }
  70507. return newValue;
  70508. };
  70509. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70510. if (newValue !== currentValue) {
  70511. if (newValue === 1) {
  70512. if (this._ondpaddown) {
  70513. this._ondpaddown(buttonType);
  70514. }
  70515. this.onPadDownObservable.notifyObservers(buttonType);
  70516. }
  70517. if (newValue === 0) {
  70518. if (this._ondpadup) {
  70519. this._ondpadup(buttonType);
  70520. }
  70521. this.onPadUpObservable.notifyObservers(buttonType);
  70522. }
  70523. }
  70524. return newValue;
  70525. };
  70526. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70527. /** Gets or sets value of A button */
  70528. get: function () {
  70529. return this._buttonA;
  70530. },
  70531. set: function (value) {
  70532. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70533. },
  70534. enumerable: true,
  70535. configurable: true
  70536. });
  70537. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70538. /** Gets or sets value of B button */
  70539. get: function () {
  70540. return this._buttonB;
  70541. },
  70542. set: function (value) {
  70543. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70544. },
  70545. enumerable: true,
  70546. configurable: true
  70547. });
  70548. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70549. /** Gets or sets value of X button */
  70550. get: function () {
  70551. return this._buttonX;
  70552. },
  70553. set: function (value) {
  70554. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70555. },
  70556. enumerable: true,
  70557. configurable: true
  70558. });
  70559. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70560. /** Gets or sets value of Y button */
  70561. get: function () {
  70562. return this._buttonY;
  70563. },
  70564. set: function (value) {
  70565. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70566. },
  70567. enumerable: true,
  70568. configurable: true
  70569. });
  70570. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70571. /** Gets or sets value of Start button */
  70572. get: function () {
  70573. return this._buttonStart;
  70574. },
  70575. set: function (value) {
  70576. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70577. },
  70578. enumerable: true,
  70579. configurable: true
  70580. });
  70581. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70582. /** Gets or sets value of Back button */
  70583. get: function () {
  70584. return this._buttonBack;
  70585. },
  70586. set: function (value) {
  70587. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70588. },
  70589. enumerable: true,
  70590. configurable: true
  70591. });
  70592. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70593. /** Gets or sets value of Left button */
  70594. get: function () {
  70595. return this._buttonLB;
  70596. },
  70597. set: function (value) {
  70598. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70599. },
  70600. enumerable: true,
  70601. configurable: true
  70602. });
  70603. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70604. /** Gets or sets value of Right button */
  70605. get: function () {
  70606. return this._buttonRB;
  70607. },
  70608. set: function (value) {
  70609. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70610. },
  70611. enumerable: true,
  70612. configurable: true
  70613. });
  70614. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70615. /** Gets or sets value of left stick */
  70616. get: function () {
  70617. return this._buttonLeftStick;
  70618. },
  70619. set: function (value) {
  70620. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70621. },
  70622. enumerable: true,
  70623. configurable: true
  70624. });
  70625. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70626. /** Gets or sets value of right stick */
  70627. get: function () {
  70628. return this._buttonRightStick;
  70629. },
  70630. set: function (value) {
  70631. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70632. },
  70633. enumerable: true,
  70634. configurable: true
  70635. });
  70636. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70637. /** Gets or sets value of DPad up */
  70638. get: function () {
  70639. return this._dPadUp;
  70640. },
  70641. set: function (value) {
  70642. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70643. },
  70644. enumerable: true,
  70645. configurable: true
  70646. });
  70647. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70648. /** Gets or sets value of DPad down */
  70649. get: function () {
  70650. return this._dPadDown;
  70651. },
  70652. set: function (value) {
  70653. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70654. },
  70655. enumerable: true,
  70656. configurable: true
  70657. });
  70658. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70659. /** Gets or sets value of DPad left */
  70660. get: function () {
  70661. return this._dPadLeft;
  70662. },
  70663. set: function (value) {
  70664. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70665. },
  70666. enumerable: true,
  70667. configurable: true
  70668. });
  70669. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70670. /** Gets or sets value of DPad right */
  70671. get: function () {
  70672. return this._dPadRight;
  70673. },
  70674. set: function (value) {
  70675. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70676. },
  70677. enumerable: true,
  70678. configurable: true
  70679. });
  70680. /**
  70681. * Force the gamepad to synchronize with device values
  70682. */
  70683. Xbox360Pad.prototype.update = function () {
  70684. _super.prototype.update.call(this);
  70685. if (this._isXboxOnePad) {
  70686. this.buttonA = this.browserGamepad.buttons[0].value;
  70687. this.buttonB = this.browserGamepad.buttons[1].value;
  70688. this.buttonX = this.browserGamepad.buttons[2].value;
  70689. this.buttonY = this.browserGamepad.buttons[3].value;
  70690. this.buttonLB = this.browserGamepad.buttons[4].value;
  70691. this.buttonRB = this.browserGamepad.buttons[5].value;
  70692. this.leftTrigger = this.browserGamepad.axes[2];
  70693. this.rightTrigger = this.browserGamepad.axes[5];
  70694. this.buttonBack = this.browserGamepad.buttons[9].value;
  70695. this.buttonStart = this.browserGamepad.buttons[8].value;
  70696. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70697. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70698. this.dPadUp = this.browserGamepad.buttons[11].value;
  70699. this.dPadDown = this.browserGamepad.buttons[12].value;
  70700. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70701. this.dPadRight = this.browserGamepad.buttons[14].value;
  70702. }
  70703. else {
  70704. this.buttonA = this.browserGamepad.buttons[0].value;
  70705. this.buttonB = this.browserGamepad.buttons[1].value;
  70706. this.buttonX = this.browserGamepad.buttons[2].value;
  70707. this.buttonY = this.browserGamepad.buttons[3].value;
  70708. this.buttonLB = this.browserGamepad.buttons[4].value;
  70709. this.buttonRB = this.browserGamepad.buttons[5].value;
  70710. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70711. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70712. this.buttonBack = this.browserGamepad.buttons[8].value;
  70713. this.buttonStart = this.browserGamepad.buttons[9].value;
  70714. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70715. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70716. this.dPadUp = this.browserGamepad.buttons[12].value;
  70717. this.dPadDown = this.browserGamepad.buttons[13].value;
  70718. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70719. this.dPadRight = this.browserGamepad.buttons[15].value;
  70720. }
  70721. };
  70722. Xbox360Pad.prototype.dispose = function () {
  70723. _super.prototype.dispose.call(this);
  70724. this.onButtonDownObservable.clear();
  70725. this.onButtonUpObservable.clear();
  70726. this.onPadDownObservable.clear();
  70727. this.onPadUpObservable.clear();
  70728. };
  70729. return Xbox360Pad;
  70730. }(BABYLON.Gamepad));
  70731. BABYLON.Xbox360Pad = Xbox360Pad;
  70732. })(BABYLON || (BABYLON = {}));
  70733. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70734. var BABYLON;
  70735. (function (BABYLON) {
  70736. /**
  70737. * Defines the types of pose enabled controllers that are supported
  70738. */
  70739. var PoseEnabledControllerType;
  70740. (function (PoseEnabledControllerType) {
  70741. /**
  70742. * HTC Vive
  70743. */
  70744. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70745. /**
  70746. * Oculus Rift
  70747. */
  70748. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70749. /**
  70750. * Windows mixed reality
  70751. */
  70752. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70753. /**
  70754. * Samsung gear VR
  70755. */
  70756. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70757. /**
  70758. * Google Daydream
  70759. */
  70760. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70761. /**
  70762. * Generic
  70763. */
  70764. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70765. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70766. /**
  70767. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70768. */
  70769. var PoseEnabledControllerHelper = /** @class */ (function () {
  70770. function PoseEnabledControllerHelper() {
  70771. }
  70772. /**
  70773. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70774. * @param vrGamepad the gamepad to initialized
  70775. * @returns a vr controller of the type the gamepad identified as
  70776. */
  70777. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70778. // Oculus Touch
  70779. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70780. return new BABYLON.OculusTouchController(vrGamepad);
  70781. }
  70782. // Windows Mixed Reality controllers
  70783. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70784. return new BABYLON.WindowsMotionController(vrGamepad);
  70785. }
  70786. // HTC Vive
  70787. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70788. return new BABYLON.ViveController(vrGamepad);
  70789. }
  70790. // Samsung/Oculus Gear VR
  70791. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70792. return new BABYLON.GearVRController(vrGamepad);
  70793. }
  70794. // Google Daydream
  70795. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70796. return new BABYLON.DaydreamController(vrGamepad);
  70797. }
  70798. // Generic
  70799. else {
  70800. return new BABYLON.GenericController(vrGamepad);
  70801. }
  70802. };
  70803. return PoseEnabledControllerHelper;
  70804. }());
  70805. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70806. /**
  70807. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70808. */
  70809. var PoseEnabledController = /** @class */ (function (_super) {
  70810. __extends(PoseEnabledController, _super);
  70811. /**
  70812. * Creates a new PoseEnabledController from a gamepad
  70813. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70814. */
  70815. function PoseEnabledController(browserGamepad) {
  70816. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70817. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70818. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70819. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70820. /**
  70821. * The device position in babylon space
  70822. */
  70823. _this.devicePosition = BABYLON.Vector3.Zero();
  70824. /**
  70825. * The device rotation in babylon space
  70826. */
  70827. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70828. /**
  70829. * The scale factor of the device in babylon space
  70830. */
  70831. _this.deviceScaleFactor = 1;
  70832. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70833. /**
  70834. * Internal, matrix used to convert room space to babylon space
  70835. */
  70836. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70837. /**
  70838. * Node to be used when casting a ray from the controller
  70839. */
  70840. _this._pointingPoseNode = null;
  70841. _this._workingMatrix = BABYLON.Matrix.Identity();
  70842. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70843. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70844. _this.position = BABYLON.Vector3.Zero();
  70845. _this.rotationQuaternion = new BABYLON.Quaternion();
  70846. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70847. _this._calculatedRotation = new BABYLON.Quaternion();
  70848. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70849. return _this;
  70850. }
  70851. /**
  70852. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70853. */
  70854. PoseEnabledController.prototype.update = function () {
  70855. _super.prototype.update.call(this);
  70856. var pose = this.browserGamepad.pose;
  70857. this.updateFromDevice(pose);
  70858. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70859. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70860. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70861. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70862. if (this._mesh) {
  70863. this._mesh.position.copyFrom(this.devicePosition);
  70864. if (this._mesh.rotationQuaternion) {
  70865. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70866. }
  70867. }
  70868. };
  70869. /**
  70870. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70871. * @param poseData raw pose fromthe device
  70872. */
  70873. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70874. if (poseData) {
  70875. this.rawPose = poseData;
  70876. if (poseData.position) {
  70877. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70878. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70879. this._deviceRoomPosition.z *= -1;
  70880. }
  70881. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70882. this._calculatedPosition.addInPlace(this.position);
  70883. }
  70884. var pose = this.rawPose;
  70885. if (poseData.orientation && pose.orientation) {
  70886. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70887. if (this._mesh) {
  70888. if (this._mesh.getScene().useRightHandedSystem) {
  70889. this._deviceRoomRotationQuaternion.z *= -1;
  70890. this._deviceRoomRotationQuaternion.w *= -1;
  70891. }
  70892. else {
  70893. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70894. }
  70895. }
  70896. // if the camera is set, rotate to the camera's rotation
  70897. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70898. }
  70899. }
  70900. };
  70901. /**
  70902. * Attaches a mesh to the controller
  70903. * @param mesh the mesh to be attached
  70904. */
  70905. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70906. if (this._mesh) {
  70907. this._mesh.parent = null;
  70908. }
  70909. this._mesh = mesh;
  70910. if (this._poseControlledCamera) {
  70911. this._mesh.parent = this._poseControlledCamera;
  70912. }
  70913. if (!this._mesh.rotationQuaternion) {
  70914. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70915. }
  70916. };
  70917. /**
  70918. * Attaches the controllers mesh to a camera
  70919. * @param camera the camera the mesh should be attached to
  70920. */
  70921. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70922. this._poseControlledCamera = camera;
  70923. if (this._mesh) {
  70924. this._mesh.parent = this._poseControlledCamera;
  70925. }
  70926. };
  70927. /**
  70928. * Disposes of the controller
  70929. */
  70930. PoseEnabledController.prototype.dispose = function () {
  70931. if (this._mesh) {
  70932. this._mesh.dispose();
  70933. }
  70934. this._mesh = null;
  70935. _super.prototype.dispose.call(this);
  70936. };
  70937. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70938. /**
  70939. * The mesh that is attached to the controller
  70940. */
  70941. get: function () {
  70942. return this._mesh;
  70943. },
  70944. enumerable: true,
  70945. configurable: true
  70946. });
  70947. /**
  70948. * Gets the ray of the controller in the direction the controller is pointing
  70949. * @param length the length the resulting ray should be
  70950. * @returns a ray in the direction the controller is pointing
  70951. */
  70952. PoseEnabledController.prototype.getForwardRay = function (length) {
  70953. if (length === void 0) { length = 100; }
  70954. if (!this.mesh) {
  70955. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70956. }
  70957. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70958. var origin = m.getTranslation();
  70959. var forward = new BABYLON.Vector3(0, 0, -1);
  70960. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70961. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70962. return new BABYLON.Ray(origin, direction, length);
  70963. };
  70964. /**
  70965. * Name of the child mesh that can be used to cast a ray from the controller
  70966. */
  70967. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70968. return PoseEnabledController;
  70969. }(BABYLON.Gamepad));
  70970. BABYLON.PoseEnabledController = PoseEnabledController;
  70971. })(BABYLON || (BABYLON = {}));
  70972. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70973. var BABYLON;
  70974. (function (BABYLON) {
  70975. /**
  70976. * Defines the WebVRController object that represents controllers tracked in 3D space
  70977. */
  70978. var WebVRController = /** @class */ (function (_super) {
  70979. __extends(WebVRController, _super);
  70980. /**
  70981. * Creates a new WebVRController from a gamepad
  70982. * @param vrGamepad the gamepad that the WebVRController should be created from
  70983. */
  70984. function WebVRController(vrGamepad) {
  70985. var _this = _super.call(this, vrGamepad) || this;
  70986. // Observables
  70987. /**
  70988. * Fired when the trigger state has changed
  70989. */
  70990. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70991. /**
  70992. * Fired when the main button state has changed
  70993. */
  70994. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70995. /**
  70996. * Fired when the secondary button state has changed
  70997. */
  70998. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70999. /**
  71000. * Fired when the pad state has changed
  71001. */
  71002. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71003. /**
  71004. * Fired when controllers stick values have changed
  71005. */
  71006. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71007. /**
  71008. * X and Y axis corrisponding to the controllers joystick
  71009. */
  71010. _this.pad = { x: 0, y: 0 };
  71011. // avoid GC, store state in a tmp object
  71012. _this._changes = {
  71013. pressChanged: false,
  71014. touchChanged: false,
  71015. valueChanged: false,
  71016. changed: false
  71017. };
  71018. _this._buttons = new Array(vrGamepad.buttons.length);
  71019. _this.hand = vrGamepad.hand;
  71020. return _this;
  71021. }
  71022. /**
  71023. * Fired when a controller button's state has changed
  71024. * @param callback the callback containing the button that was modified
  71025. */
  71026. WebVRController.prototype.onButtonStateChange = function (callback) {
  71027. this._onButtonStateChange = callback;
  71028. };
  71029. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71030. /**
  71031. * The default controller model for the controller
  71032. */
  71033. get: function () {
  71034. return this._defaultModel;
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. /**
  71040. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71041. */
  71042. WebVRController.prototype.update = function () {
  71043. _super.prototype.update.call(this);
  71044. for (var index = 0; index < this._buttons.length; index++) {
  71045. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71046. }
  71047. ;
  71048. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71049. this.pad.x = this.leftStick.x;
  71050. this.pad.y = this.leftStick.y;
  71051. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71052. }
  71053. };
  71054. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71055. if (!newState) {
  71056. newState = {
  71057. pressed: false,
  71058. touched: false,
  71059. value: 0
  71060. };
  71061. }
  71062. if (!currentState) {
  71063. this._buttons[buttonIndex] = {
  71064. pressed: newState.pressed,
  71065. touched: newState.touched,
  71066. value: newState.value
  71067. };
  71068. return;
  71069. }
  71070. this._checkChanges(newState, currentState);
  71071. if (this._changes.changed) {
  71072. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71073. this._handleButtonChange(buttonIndex, newState, this._changes);
  71074. }
  71075. this._buttons[buttonIndex].pressed = newState.pressed;
  71076. this._buttons[buttonIndex].touched = newState.touched;
  71077. // oculus triggers are never 0, thou not touched.
  71078. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71079. };
  71080. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71081. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71082. this._changes.touchChanged = newState.touched !== currentState.touched;
  71083. this._changes.valueChanged = newState.value !== currentState.value;
  71084. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71085. return this._changes;
  71086. };
  71087. /**
  71088. * Disposes of th webVRCOntroller
  71089. */
  71090. WebVRController.prototype.dispose = function () {
  71091. _super.prototype.dispose.call(this);
  71092. this.onTriggerStateChangedObservable.clear();
  71093. this.onMainButtonStateChangedObservable.clear();
  71094. this.onSecondaryButtonStateChangedObservable.clear();
  71095. this.onPadStateChangedObservable.clear();
  71096. this.onPadValuesChangedObservable.clear();
  71097. };
  71098. return WebVRController;
  71099. }(BABYLON.PoseEnabledController));
  71100. BABYLON.WebVRController = WebVRController;
  71101. })(BABYLON || (BABYLON = {}));
  71102. //# sourceMappingURL=babylon.webVRController.js.map
  71103. var BABYLON;
  71104. (function (BABYLON) {
  71105. /**
  71106. * Oculus Touch Controller
  71107. */
  71108. var OculusTouchController = /** @class */ (function (_super) {
  71109. __extends(OculusTouchController, _super);
  71110. /**
  71111. * Creates a new OculusTouchController from a gamepad
  71112. * @param vrGamepad the gamepad that the controller should be created from
  71113. */
  71114. function OculusTouchController(vrGamepad) {
  71115. var _this = _super.call(this, vrGamepad) || this;
  71116. /**
  71117. * Fired when the secondary trigger on this controller is modified
  71118. */
  71119. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71120. /**
  71121. * Fired when the thumb rest on this controller is modified
  71122. */
  71123. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71124. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71125. return _this;
  71126. }
  71127. /**
  71128. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71129. * @param scene scene in which to add meshes
  71130. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71131. */
  71132. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71133. var _this = this;
  71134. var meshName;
  71135. // Hand
  71136. if (this.hand === 'left') {
  71137. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71138. }
  71139. else { // Right is the default if no hand is specified
  71140. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71141. }
  71142. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71143. /*
  71144. Parent Mesh name: oculus_touch_left
  71145. - body
  71146. - trigger
  71147. - thumbstick
  71148. - grip
  71149. - button_y
  71150. - button_x
  71151. - button_enter
  71152. */
  71153. _this._defaultModel = newMeshes[1];
  71154. _this.attachToMesh(_this._defaultModel);
  71155. if (meshLoaded) {
  71156. meshLoaded(_this._defaultModel);
  71157. }
  71158. });
  71159. };
  71160. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71161. /**
  71162. * Fired when the A button on this controller is modified
  71163. */
  71164. get: function () {
  71165. if (this.hand === 'right') {
  71166. return this.onMainButtonStateChangedObservable;
  71167. }
  71168. else {
  71169. throw new Error('No A button on left hand');
  71170. }
  71171. },
  71172. enumerable: true,
  71173. configurable: true
  71174. });
  71175. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71176. /**
  71177. * Fired when the B button on this controller is modified
  71178. */
  71179. get: function () {
  71180. if (this.hand === 'right') {
  71181. return this.onSecondaryButtonStateChangedObservable;
  71182. }
  71183. else {
  71184. throw new Error('No B button on left hand');
  71185. }
  71186. },
  71187. enumerable: true,
  71188. configurable: true
  71189. });
  71190. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71191. /**
  71192. * Fired when the X button on this controller is modified
  71193. */
  71194. get: function () {
  71195. if (this.hand === 'left') {
  71196. return this.onMainButtonStateChangedObservable;
  71197. }
  71198. else {
  71199. throw new Error('No X button on right hand');
  71200. }
  71201. },
  71202. enumerable: true,
  71203. configurable: true
  71204. });
  71205. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71206. /**
  71207. * Fired when the Y button on this controller is modified
  71208. */
  71209. get: function () {
  71210. if (this.hand === 'left') {
  71211. return this.onSecondaryButtonStateChangedObservable;
  71212. }
  71213. else {
  71214. throw new Error('No Y button on right hand');
  71215. }
  71216. },
  71217. enumerable: true,
  71218. configurable: true
  71219. });
  71220. /**
  71221. * Called once for each button that changed state since the last frame
  71222. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71223. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71224. * 2) secondary trigger (same)
  71225. * 3) A (right) X (left), touch, pressed = value
  71226. * 4) B / Y
  71227. * 5) thumb rest
  71228. * @param buttonIdx Which button index changed
  71229. * @param state New state of the button
  71230. * @param changes Which properties on the state changed since last frame
  71231. */
  71232. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71233. var notifyObject = state; //{ state: state, changes: changes };
  71234. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71235. switch (buttonIdx) {
  71236. case 0:
  71237. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71238. return;
  71239. case 1: // index trigger
  71240. if (this._defaultModel) {
  71241. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71242. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71243. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71244. }
  71245. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71246. return;
  71247. case 2: // secondary trigger
  71248. if (this._defaultModel) {
  71249. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71250. }
  71251. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71252. return;
  71253. case 3:
  71254. if (this._defaultModel) {
  71255. if (notifyObject.pressed) {
  71256. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71257. }
  71258. else {
  71259. (this._defaultModel.getChildren()[1]).position.y = 0;
  71260. }
  71261. }
  71262. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71263. return;
  71264. case 4:
  71265. if (this._defaultModel) {
  71266. if (notifyObject.pressed) {
  71267. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71268. }
  71269. else {
  71270. (this._defaultModel.getChildren()[2]).position.y = 0;
  71271. }
  71272. }
  71273. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71274. return;
  71275. case 5:
  71276. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71277. return;
  71278. }
  71279. };
  71280. /**
  71281. * Base Url for the controller model.
  71282. */
  71283. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71284. /**
  71285. * File name for the left controller model.
  71286. */
  71287. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71288. /**
  71289. * File name for the right controller model.
  71290. */
  71291. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71292. return OculusTouchController;
  71293. }(BABYLON.WebVRController));
  71294. BABYLON.OculusTouchController = OculusTouchController;
  71295. })(BABYLON || (BABYLON = {}));
  71296. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71297. var BABYLON;
  71298. (function (BABYLON) {
  71299. /**
  71300. * Vive Controller
  71301. */
  71302. var ViveController = /** @class */ (function (_super) {
  71303. __extends(ViveController, _super);
  71304. /**
  71305. * Creates a new ViveController from a gamepad
  71306. * @param vrGamepad the gamepad that the controller should be created from
  71307. */
  71308. function ViveController(vrGamepad) {
  71309. var _this = _super.call(this, vrGamepad) || this;
  71310. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71311. _this._invertLeftStickY = true;
  71312. return _this;
  71313. }
  71314. /**
  71315. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71316. * @param scene scene in which to add meshes
  71317. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71318. */
  71319. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71320. var _this = this;
  71321. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71322. /*
  71323. Parent Mesh name: ViveWand
  71324. - body
  71325. - r_gripper
  71326. - l_gripper
  71327. - menu_button
  71328. - system_button
  71329. - trackpad
  71330. - trigger
  71331. - LED
  71332. */
  71333. _this._defaultModel = newMeshes[1];
  71334. _this.attachToMesh(_this._defaultModel);
  71335. if (meshLoaded) {
  71336. meshLoaded(_this._defaultModel);
  71337. }
  71338. });
  71339. };
  71340. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71341. /**
  71342. * Fired when the left button on this controller is modified
  71343. */
  71344. get: function () {
  71345. return this.onMainButtonStateChangedObservable;
  71346. },
  71347. enumerable: true,
  71348. configurable: true
  71349. });
  71350. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71351. /**
  71352. * Fired when the right button on this controller is modified
  71353. */
  71354. get: function () {
  71355. return this.onMainButtonStateChangedObservable;
  71356. },
  71357. enumerable: true,
  71358. configurable: true
  71359. });
  71360. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71361. /**
  71362. * Fired when the menu button on this controller is modified
  71363. */
  71364. get: function () {
  71365. return this.onSecondaryButtonStateChangedObservable;
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. /**
  71371. * Called once for each button that changed state since the last frame
  71372. * Vive mapping:
  71373. * 0: touchpad
  71374. * 1: trigger
  71375. * 2: left AND right buttons
  71376. * 3: menu button
  71377. * @param buttonIdx Which button index changed
  71378. * @param state New state of the button
  71379. * @param changes Which properties on the state changed since last frame
  71380. */
  71381. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71382. var notifyObject = state; //{ state: state, changes: changes };
  71383. switch (buttonIdx) {
  71384. case 0:
  71385. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71386. return;
  71387. case 1: // index trigger
  71388. if (this._defaultModel) {
  71389. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71390. }
  71391. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71392. return;
  71393. case 2: // left AND right button
  71394. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71395. return;
  71396. case 3:
  71397. if (this._defaultModel) {
  71398. if (notifyObject.pressed) {
  71399. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71400. }
  71401. else {
  71402. (this._defaultModel.getChildren()[2]).position.y = 0;
  71403. }
  71404. }
  71405. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71406. return;
  71407. }
  71408. };
  71409. /**
  71410. * Base Url for the controller model.
  71411. */
  71412. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71413. /**
  71414. * File name for the controller model.
  71415. */
  71416. ViveController.MODEL_FILENAME = 'wand.babylon';
  71417. return ViveController;
  71418. }(BABYLON.WebVRController));
  71419. BABYLON.ViveController = ViveController;
  71420. })(BABYLON || (BABYLON = {}));
  71421. //# sourceMappingURL=babylon.viveController.js.map
  71422. var BABYLON;
  71423. (function (BABYLON) {
  71424. /**
  71425. * Generic Controller
  71426. */
  71427. var GenericController = /** @class */ (function (_super) {
  71428. __extends(GenericController, _super);
  71429. /**
  71430. * Creates a new GenericController from a gamepad
  71431. * @param vrGamepad the gamepad that the controller should be created from
  71432. */
  71433. function GenericController(vrGamepad) {
  71434. return _super.call(this, vrGamepad) || this;
  71435. }
  71436. /**
  71437. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71438. * @param scene scene in which to add meshes
  71439. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71440. */
  71441. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71442. var _this = this;
  71443. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71444. _this._defaultModel = newMeshes[1];
  71445. _this.attachToMesh(_this._defaultModel);
  71446. if (meshLoaded) {
  71447. meshLoaded(_this._defaultModel);
  71448. }
  71449. });
  71450. };
  71451. /**
  71452. * Called once for each button that changed state since the last frame
  71453. * @param buttonIdx Which button index changed
  71454. * @param state New state of the button
  71455. * @param changes Which properties on the state changed since last frame
  71456. */
  71457. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71458. console.log("Button id: " + buttonIdx + "state: ");
  71459. console.dir(state);
  71460. };
  71461. /**
  71462. * Base Url for the controller model.
  71463. */
  71464. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71465. /**
  71466. * File name for the controller model.
  71467. */
  71468. GenericController.MODEL_FILENAME = 'generic.babylon';
  71469. return GenericController;
  71470. }(BABYLON.WebVRController));
  71471. BABYLON.GenericController = GenericController;
  71472. })(BABYLON || (BABYLON = {}));
  71473. //# sourceMappingURL=babylon.genericController.js.map
  71474. var BABYLON;
  71475. (function (BABYLON) {
  71476. /**
  71477. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71478. */
  71479. var LoadedMeshInfo = /** @class */ (function () {
  71480. function LoadedMeshInfo() {
  71481. /**
  71482. * Map of the button meshes contained in the controller
  71483. */
  71484. this.buttonMeshes = {};
  71485. /**
  71486. * Map of the axis meshes contained in the controller
  71487. */
  71488. this.axisMeshes = {};
  71489. }
  71490. return LoadedMeshInfo;
  71491. }());
  71492. /**
  71493. * Defines the WindowsMotionController object that the state of the windows motion controller
  71494. */
  71495. var WindowsMotionController = /** @class */ (function (_super) {
  71496. __extends(WindowsMotionController, _super);
  71497. /**
  71498. * Creates a new WindowsMotionController from a gamepad
  71499. * @param vrGamepad the gamepad that the controller should be created from
  71500. */
  71501. function WindowsMotionController(vrGamepad) {
  71502. var _this = _super.call(this, vrGamepad) || this;
  71503. _this._mapping = {
  71504. // Semantic button names
  71505. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71506. // A mapping of the button name to glTF model node name
  71507. // that should be transformed by button value.
  71508. buttonMeshNames: {
  71509. 'trigger': 'SELECT',
  71510. 'menu': 'MENU',
  71511. 'grip': 'GRASP',
  71512. 'thumbstick': 'THUMBSTICK_PRESS',
  71513. 'trackpad': 'TOUCHPAD_PRESS'
  71514. },
  71515. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71516. buttonObservableNames: {
  71517. 'trigger': 'onTriggerStateChangedObservable',
  71518. 'menu': 'onSecondaryButtonStateChangedObservable',
  71519. 'grip': 'onMainButtonStateChangedObservable',
  71520. 'thumbstick': 'onPadStateChangedObservable',
  71521. 'trackpad': 'onTrackpadChangedObservable'
  71522. },
  71523. // A mapping of the axis name to glTF model node name
  71524. // that should be transformed by axis value.
  71525. // This array mirrors the browserGamepad.axes array, such that
  71526. // the mesh corresponding to axis 0 is in this array index 0.
  71527. axisMeshNames: [
  71528. 'THUMBSTICK_X',
  71529. 'THUMBSTICK_Y',
  71530. 'TOUCHPAD_TOUCH_X',
  71531. 'TOUCHPAD_TOUCH_Y'
  71532. ],
  71533. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71534. };
  71535. /**
  71536. * Fired when the trackpad on this controller is clicked
  71537. */
  71538. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71539. /**
  71540. * Fired when the trackpad on this controller is modified
  71541. */
  71542. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71543. /**
  71544. * The current x and y values of this controller's trackpad
  71545. */
  71546. _this.trackpad = { x: 0, y: 0 };
  71547. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71548. _this._loadedMeshInfo = null;
  71549. return _this;
  71550. }
  71551. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71552. /**
  71553. * Fired when the trigger on this controller is modified
  71554. */
  71555. get: function () {
  71556. return this.onTriggerStateChangedObservable;
  71557. },
  71558. enumerable: true,
  71559. configurable: true
  71560. });
  71561. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71562. /**
  71563. * Fired when the menu button on this controller is modified
  71564. */
  71565. get: function () {
  71566. return this.onSecondaryButtonStateChangedObservable;
  71567. },
  71568. enumerable: true,
  71569. configurable: true
  71570. });
  71571. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71572. /**
  71573. * Fired when the grip button on this controller is modified
  71574. */
  71575. get: function () {
  71576. return this.onMainButtonStateChangedObservable;
  71577. },
  71578. enumerable: true,
  71579. configurable: true
  71580. });
  71581. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71582. /**
  71583. * Fired when the thumbstick button on this controller is modified
  71584. */
  71585. get: function () {
  71586. return this.onPadStateChangedObservable;
  71587. },
  71588. enumerable: true,
  71589. configurable: true
  71590. });
  71591. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71592. /**
  71593. * Fired when the touchpad button on this controller is modified
  71594. */
  71595. get: function () {
  71596. return this.onTrackpadChangedObservable;
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71602. /**
  71603. * Fired when the touchpad values on this controller are modified
  71604. */
  71605. get: function () {
  71606. return this.onTrackpadValuesChangedObservable;
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. /**
  71612. * Called once per frame by the engine.
  71613. */
  71614. WindowsMotionController.prototype.update = function () {
  71615. _super.prototype.update.call(this);
  71616. if (this.browserGamepad.axes) {
  71617. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71618. this.trackpad.x = this.browserGamepad["axes"][2];
  71619. this.trackpad.y = this.browserGamepad["axes"][3];
  71620. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71621. }
  71622. // Only need to animate axes if there is a loaded mesh
  71623. if (this._loadedMeshInfo) {
  71624. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71625. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71626. }
  71627. }
  71628. }
  71629. };
  71630. /**
  71631. * Called once for each button that changed state since the last frame
  71632. * @param buttonIdx Which button index changed
  71633. * @param state New state of the button
  71634. * @param changes Which properties on the state changed since last frame
  71635. */
  71636. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71637. var buttonName = this._mapping.buttons[buttonIdx];
  71638. if (!buttonName) {
  71639. return;
  71640. }
  71641. // Only emit events for buttons that we know how to map from index to name
  71642. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71643. if (observable) {
  71644. observable.notifyObservers(state);
  71645. }
  71646. this._lerpButtonTransform(buttonName, state.value);
  71647. };
  71648. /**
  71649. * Moves the buttons on the controller mesh based on their current state
  71650. * @param buttonName the name of the button to move
  71651. * @param buttonValue the value of the button which determines the buttons new position
  71652. */
  71653. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71654. // If there is no loaded mesh, there is nothing to transform.
  71655. if (!this._loadedMeshInfo) {
  71656. return;
  71657. }
  71658. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71659. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71660. return;
  71661. }
  71662. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71663. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71664. };
  71665. /**
  71666. * Moves the axis on the controller mesh based on its current state
  71667. * @param axis the index of the axis
  71668. * @param axisValue the value of the axis which determines the meshes new position
  71669. * @hidden
  71670. */
  71671. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71672. if (!this._loadedMeshInfo) {
  71673. return;
  71674. }
  71675. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71676. if (!meshInfo) {
  71677. return;
  71678. }
  71679. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71680. return;
  71681. }
  71682. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71683. var lerpValue = axisValue * 0.5 + 0.5;
  71684. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71685. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71686. };
  71687. /**
  71688. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71689. * @param scene scene in which to add meshes
  71690. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71691. */
  71692. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71693. var _this = this;
  71694. if (forceDefault === void 0) { forceDefault = false; }
  71695. var path;
  71696. var filename;
  71697. // Checking if GLB loader is present
  71698. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71699. // Determine the device specific folder based on the ID suffix
  71700. var device = 'default';
  71701. if (this.id && !forceDefault) {
  71702. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71703. device = ((match && match[0]) || device);
  71704. }
  71705. // Hand
  71706. if (this.hand === 'left') {
  71707. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71708. }
  71709. else { // Right is the default if no hand is specified
  71710. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71711. }
  71712. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71713. }
  71714. else {
  71715. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71716. path = BABYLON.GenericController.MODEL_BASE_URL;
  71717. filename = BABYLON.GenericController.MODEL_FILENAME;
  71718. }
  71719. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71720. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71721. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71722. if (!_this._loadedMeshInfo) {
  71723. return;
  71724. }
  71725. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71726. _this.attachToMesh(_this._defaultModel);
  71727. if (meshLoaded) {
  71728. meshLoaded(_this._defaultModel);
  71729. }
  71730. }, null, function (scene, message) {
  71731. BABYLON.Tools.Log(message);
  71732. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71733. if (!forceDefault) {
  71734. _this.initControllerMesh(scene, meshLoaded, true);
  71735. }
  71736. });
  71737. };
  71738. /**
  71739. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71740. * can be transformed by button presses and axes values, based on this._mapping.
  71741. *
  71742. * @param scene scene in which the meshes exist
  71743. * @param meshes list of meshes that make up the controller model to process
  71744. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71745. */
  71746. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71747. var loadedMeshInfo = null;
  71748. // Create a new mesh to contain the glTF hierarchy
  71749. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71750. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71751. var childMesh = null;
  71752. for (var i = 0; i < meshes.length; i++) {
  71753. var mesh = meshes[i];
  71754. if (!mesh.parent) {
  71755. // Exclude controller meshes from picking results
  71756. mesh.isPickable = false;
  71757. // Handle root node, attach to the new parentMesh
  71758. childMesh = mesh;
  71759. break;
  71760. }
  71761. }
  71762. if (childMesh) {
  71763. childMesh.setParent(parentMesh);
  71764. // Create our mesh info. Note that this method will always return non-null.
  71765. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71766. }
  71767. else {
  71768. BABYLON.Tools.Warn('Could not find root node in model file.');
  71769. }
  71770. return loadedMeshInfo;
  71771. };
  71772. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71773. var loadedMeshInfo = new LoadedMeshInfo();
  71774. var i;
  71775. loadedMeshInfo.rootNode = rootNode;
  71776. // Reset the caches
  71777. loadedMeshInfo.buttonMeshes = {};
  71778. loadedMeshInfo.axisMeshes = {};
  71779. // Button Meshes
  71780. for (i = 0; i < this._mapping.buttons.length; i++) {
  71781. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71782. if (!buttonMeshName) {
  71783. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71784. continue;
  71785. }
  71786. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71787. if (!buttonMesh) {
  71788. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71789. continue;
  71790. }
  71791. var buttonMeshInfo = {
  71792. index: i,
  71793. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71794. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71795. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71796. };
  71797. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71798. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71799. }
  71800. else {
  71801. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71802. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71803. '(VALUE: ' + !!buttonMeshInfo.value +
  71804. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71805. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71806. ')');
  71807. }
  71808. }
  71809. // Axis Meshes
  71810. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71811. var axisMeshName = this._mapping.axisMeshNames[i];
  71812. if (!axisMeshName) {
  71813. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71814. continue;
  71815. }
  71816. var axisMesh = getChildByName(rootNode, axisMeshName);
  71817. if (!axisMesh) {
  71818. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71819. continue;
  71820. }
  71821. var axisMeshInfo = {
  71822. index: i,
  71823. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71824. min: getImmediateChildByName(axisMesh, 'MIN'),
  71825. max: getImmediateChildByName(axisMesh, 'MAX')
  71826. };
  71827. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71828. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71829. }
  71830. else {
  71831. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71832. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71833. '(VALUE: ' + !!axisMeshInfo.value +
  71834. ', MIN: ' + !!axisMeshInfo.min +
  71835. ', MAX:' + !!axisMeshInfo.max +
  71836. ')');
  71837. }
  71838. }
  71839. // Pointing Ray
  71840. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71841. if (!loadedMeshInfo.pointingPoseNode) {
  71842. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71843. }
  71844. return loadedMeshInfo;
  71845. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71846. function getChildByName(node, name) {
  71847. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71848. }
  71849. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71850. function getImmediateChildByName(node, name) {
  71851. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71852. }
  71853. };
  71854. /**
  71855. * Gets the ray of the controller in the direction the controller is pointing
  71856. * @param length the length the resulting ray should be
  71857. * @returns a ray in the direction the controller is pointing
  71858. */
  71859. WindowsMotionController.prototype.getForwardRay = function (length) {
  71860. if (length === void 0) { length = 100; }
  71861. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71862. return _super.prototype.getForwardRay.call(this, length);
  71863. }
  71864. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71865. var origin = m.getTranslation();
  71866. var forward = new BABYLON.Vector3(0, 0, -1);
  71867. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71868. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71869. return new BABYLON.Ray(origin, direction, length);
  71870. };
  71871. /**
  71872. * Disposes of the controller
  71873. */
  71874. WindowsMotionController.prototype.dispose = function () {
  71875. _super.prototype.dispose.call(this);
  71876. this.onTrackpadChangedObservable.clear();
  71877. };
  71878. /**
  71879. * The base url used to load the left and right controller models
  71880. */
  71881. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71882. /**
  71883. * The name of the left controller model file
  71884. */
  71885. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71886. /**
  71887. * The name of the right controller model file
  71888. */
  71889. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71890. /**
  71891. * The controller name prefix for this controller type
  71892. */
  71893. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71894. /**
  71895. * The controller id pattern for this controller type
  71896. */
  71897. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71898. return WindowsMotionController;
  71899. }(BABYLON.WebVRController));
  71900. BABYLON.WindowsMotionController = WindowsMotionController;
  71901. })(BABYLON || (BABYLON = {}));
  71902. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71903. var BABYLON;
  71904. (function (BABYLON) {
  71905. /**
  71906. * Gear VR Controller
  71907. */
  71908. var GearVRController = /** @class */ (function (_super) {
  71909. __extends(GearVRController, _super);
  71910. /**
  71911. * Creates a new GearVRController from a gamepad
  71912. * @param vrGamepad the gamepad that the controller should be created from
  71913. */
  71914. function GearVRController(vrGamepad) {
  71915. var _this = _super.call(this, vrGamepad) || this;
  71916. _this._buttonIndexToObservableNameMap = [
  71917. 'onTrackpadChangedObservable',
  71918. 'onTriggerStateChangedObservable' // Trigger
  71919. ];
  71920. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71921. return _this;
  71922. }
  71923. /**
  71924. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71925. * @param scene scene in which to add meshes
  71926. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71927. */
  71928. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71929. var _this = this;
  71930. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71931. _this._defaultModel = newMeshes[1];
  71932. _this.attachToMesh(_this._defaultModel);
  71933. if (meshLoaded) {
  71934. meshLoaded(_this._defaultModel);
  71935. }
  71936. });
  71937. };
  71938. /**
  71939. * Called once for each button that changed state since the last frame
  71940. * @param buttonIdx Which button index changed
  71941. * @param state New state of the button
  71942. * @param changes Which properties on the state changed since last frame
  71943. */
  71944. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71945. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71946. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71947. // Only emit events for buttons that we know how to map from index to observable
  71948. var observable = this[observableName];
  71949. if (observable) {
  71950. observable.notifyObservers(state);
  71951. }
  71952. }
  71953. };
  71954. /**
  71955. * Base Url for the controller model.
  71956. */
  71957. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71958. /**
  71959. * File name for the controller model.
  71960. */
  71961. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71962. /**
  71963. * Gamepad Id prefix used to identify this controller.
  71964. */
  71965. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71966. return GearVRController;
  71967. }(BABYLON.WebVRController));
  71968. BABYLON.GearVRController = GearVRController;
  71969. })(BABYLON || (BABYLON = {}));
  71970. //# sourceMappingURL=babylon.gearVRController.js.map
  71971. var BABYLON;
  71972. (function (BABYLON) {
  71973. /**
  71974. * Google Daydream controller
  71975. */
  71976. var DaydreamController = /** @class */ (function (_super) {
  71977. __extends(DaydreamController, _super);
  71978. /**
  71979. * Creates a new DaydreamController from a gamepad
  71980. * @param vrGamepad the gamepad that the controller should be created from
  71981. */
  71982. function DaydreamController(vrGamepad) {
  71983. var _this = _super.call(this, vrGamepad) || this;
  71984. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71985. return _this;
  71986. }
  71987. /**
  71988. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71989. * @param scene scene in which to add meshes
  71990. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71991. */
  71992. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71993. var _this = this;
  71994. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71995. _this._defaultModel = newMeshes[1];
  71996. _this.attachToMesh(_this._defaultModel);
  71997. if (meshLoaded) {
  71998. meshLoaded(_this._defaultModel);
  71999. }
  72000. });
  72001. };
  72002. /**
  72003. * Called once for each button that changed state since the last frame
  72004. * @param buttonIdx Which button index changed
  72005. * @param state New state of the button
  72006. * @param changes Which properties on the state changed since last frame
  72007. */
  72008. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72009. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72010. if (buttonIdx === 0) {
  72011. var observable = this.onTriggerStateChangedObservable;
  72012. if (observable) {
  72013. observable.notifyObservers(state);
  72014. }
  72015. }
  72016. else {
  72017. // If the app or home buttons are ever made available
  72018. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72019. }
  72020. };
  72021. /**
  72022. * Base Url for the controller model.
  72023. */
  72024. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72025. /**
  72026. * File name for the controller model.
  72027. */
  72028. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72029. /**
  72030. * Gamepad Id prefix used to identify Daydream Controller.
  72031. */
  72032. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72033. return DaydreamController;
  72034. }(BABYLON.WebVRController));
  72035. BABYLON.DaydreamController = DaydreamController;
  72036. })(BABYLON || (BABYLON = {}));
  72037. //# sourceMappingURL=babylon.daydreamController.js.map
  72038. var BABYLON;
  72039. (function (BABYLON) {
  72040. var FollowCamera = /** @class */ (function (_super) {
  72041. __extends(FollowCamera, _super);
  72042. function FollowCamera(name, position, scene, lockedTarget) {
  72043. if (lockedTarget === void 0) { lockedTarget = null; }
  72044. var _this = _super.call(this, name, position, scene) || this;
  72045. _this.radius = 12;
  72046. _this.rotationOffset = 0;
  72047. _this.heightOffset = 4;
  72048. _this.cameraAcceleration = 0.05;
  72049. _this.maxCameraSpeed = 20;
  72050. _this.lockedTarget = lockedTarget;
  72051. return _this;
  72052. }
  72053. FollowCamera.prototype.getRadians = function (degrees) {
  72054. return degrees * Math.PI / 180;
  72055. };
  72056. FollowCamera.prototype.follow = function (cameraTarget) {
  72057. if (!cameraTarget)
  72058. return;
  72059. var yRotation;
  72060. if (cameraTarget.rotationQuaternion) {
  72061. var rotMatrix = new BABYLON.Matrix();
  72062. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72063. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72064. }
  72065. else {
  72066. yRotation = cameraTarget.rotation.y;
  72067. }
  72068. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72069. var targetPosition = cameraTarget.getAbsolutePosition();
  72070. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72071. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72072. var dx = targetX - this.position.x;
  72073. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72074. var dz = (targetZ) - this.position.z;
  72075. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72076. var vy = dy * this.cameraAcceleration;
  72077. var vz = dz * this.cameraAcceleration * 2;
  72078. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72079. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72080. }
  72081. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72082. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72083. }
  72084. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72085. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72086. }
  72087. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72088. this.setTarget(targetPosition);
  72089. };
  72090. FollowCamera.prototype._checkInputs = function () {
  72091. _super.prototype._checkInputs.call(this);
  72092. if (this.lockedTarget) {
  72093. this.follow(this.lockedTarget);
  72094. }
  72095. };
  72096. FollowCamera.prototype.getClassName = function () {
  72097. return "FollowCamera";
  72098. };
  72099. __decorate([
  72100. BABYLON.serialize()
  72101. ], FollowCamera.prototype, "radius", void 0);
  72102. __decorate([
  72103. BABYLON.serialize()
  72104. ], FollowCamera.prototype, "rotationOffset", void 0);
  72105. __decorate([
  72106. BABYLON.serialize()
  72107. ], FollowCamera.prototype, "heightOffset", void 0);
  72108. __decorate([
  72109. BABYLON.serialize()
  72110. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72111. __decorate([
  72112. BABYLON.serialize()
  72113. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72114. __decorate([
  72115. BABYLON.serializeAsMeshReference("lockedTargetId")
  72116. ], FollowCamera.prototype, "lockedTarget", void 0);
  72117. return FollowCamera;
  72118. }(BABYLON.TargetCamera));
  72119. BABYLON.FollowCamera = FollowCamera;
  72120. var ArcFollowCamera = /** @class */ (function (_super) {
  72121. __extends(ArcFollowCamera, _super);
  72122. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72123. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72124. _this.alpha = alpha;
  72125. _this.beta = beta;
  72126. _this.radius = radius;
  72127. _this.target = target;
  72128. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72129. _this.follow();
  72130. return _this;
  72131. }
  72132. ArcFollowCamera.prototype.follow = function () {
  72133. if (!this.target) {
  72134. return;
  72135. }
  72136. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72137. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72138. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72139. var targetPosition = this.target.getAbsolutePosition();
  72140. this.position = targetPosition.add(this._cartesianCoordinates);
  72141. this.setTarget(targetPosition);
  72142. };
  72143. ArcFollowCamera.prototype._checkInputs = function () {
  72144. _super.prototype._checkInputs.call(this);
  72145. this.follow();
  72146. };
  72147. ArcFollowCamera.prototype.getClassName = function () {
  72148. return "ArcFollowCamera";
  72149. };
  72150. return ArcFollowCamera;
  72151. }(BABYLON.TargetCamera));
  72152. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72153. })(BABYLON || (BABYLON = {}));
  72154. //# sourceMappingURL=babylon.followCamera.js.map
  72155. var BABYLON;
  72156. (function (BABYLON) {
  72157. // We're mainly based on the logic defined into the FreeCamera code
  72158. var UniversalCamera = /** @class */ (function (_super) {
  72159. __extends(UniversalCamera, _super);
  72160. //-- end properties for backward compatibility for inputs
  72161. function UniversalCamera(name, position, scene) {
  72162. var _this = _super.call(this, name, position, scene) || this;
  72163. _this.inputs.addGamepad();
  72164. return _this;
  72165. }
  72166. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72167. //-- Begin properties for backward compatibility for inputs
  72168. get: function () {
  72169. var gamepad = this.inputs.attached["gamepad"];
  72170. if (gamepad)
  72171. return gamepad.gamepadAngularSensibility;
  72172. return 0;
  72173. },
  72174. set: function (value) {
  72175. var gamepad = this.inputs.attached["gamepad"];
  72176. if (gamepad)
  72177. gamepad.gamepadAngularSensibility = value;
  72178. },
  72179. enumerable: true,
  72180. configurable: true
  72181. });
  72182. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72183. get: function () {
  72184. var gamepad = this.inputs.attached["gamepad"];
  72185. if (gamepad)
  72186. return gamepad.gamepadMoveSensibility;
  72187. return 0;
  72188. },
  72189. set: function (value) {
  72190. var gamepad = this.inputs.attached["gamepad"];
  72191. if (gamepad)
  72192. gamepad.gamepadMoveSensibility = value;
  72193. },
  72194. enumerable: true,
  72195. configurable: true
  72196. });
  72197. UniversalCamera.prototype.getClassName = function () {
  72198. return "UniversalCamera";
  72199. };
  72200. return UniversalCamera;
  72201. }(BABYLON.TouchCamera));
  72202. BABYLON.UniversalCamera = UniversalCamera;
  72203. })(BABYLON || (BABYLON = {}));
  72204. //# sourceMappingURL=babylon.universalCamera.js.map
  72205. var BABYLON;
  72206. (function (BABYLON) {
  72207. // We're mainly based on the logic defined into the FreeCamera code
  72208. var GamepadCamera = /** @class */ (function (_super) {
  72209. __extends(GamepadCamera, _super);
  72210. //-- end properties for backward compatibility for inputs
  72211. function GamepadCamera(name, position, scene) {
  72212. return _super.call(this, name, position, scene) || this;
  72213. }
  72214. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72215. //-- Begin properties for backward compatibility for inputs
  72216. get: function () {
  72217. var gamepad = this.inputs.attached["gamepad"];
  72218. if (gamepad)
  72219. return gamepad.gamepadAngularSensibility;
  72220. return 0;
  72221. },
  72222. set: function (value) {
  72223. var gamepad = this.inputs.attached["gamepad"];
  72224. if (gamepad)
  72225. gamepad.gamepadAngularSensibility = value;
  72226. },
  72227. enumerable: true,
  72228. configurable: true
  72229. });
  72230. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72231. get: function () {
  72232. var gamepad = this.inputs.attached["gamepad"];
  72233. if (gamepad)
  72234. return gamepad.gamepadMoveSensibility;
  72235. return 0;
  72236. },
  72237. set: function (value) {
  72238. var gamepad = this.inputs.attached["gamepad"];
  72239. if (gamepad)
  72240. gamepad.gamepadMoveSensibility = value;
  72241. },
  72242. enumerable: true,
  72243. configurable: true
  72244. });
  72245. GamepadCamera.prototype.getClassName = function () {
  72246. return "GamepadCamera";
  72247. };
  72248. return GamepadCamera;
  72249. }(BABYLON.UniversalCamera));
  72250. BABYLON.GamepadCamera = GamepadCamera;
  72251. })(BABYLON || (BABYLON = {}));
  72252. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72253. var BABYLON;
  72254. (function (BABYLON) {
  72255. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72256. function PostProcessRenderPipelineManager() {
  72257. this._renderPipelines = {};
  72258. }
  72259. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72260. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72261. };
  72262. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72263. if (unique === void 0) { unique = false; }
  72264. var renderPipeline = this._renderPipelines[renderPipelineName];
  72265. if (!renderPipeline) {
  72266. return;
  72267. }
  72268. renderPipeline._attachCameras(cameras, unique);
  72269. };
  72270. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72271. var renderPipeline = this._renderPipelines[renderPipelineName];
  72272. if (!renderPipeline) {
  72273. return;
  72274. }
  72275. renderPipeline._detachCameras(cameras);
  72276. };
  72277. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72278. var renderPipeline = this._renderPipelines[renderPipelineName];
  72279. if (!renderPipeline) {
  72280. return;
  72281. }
  72282. renderPipeline._enableEffect(renderEffectName, cameras);
  72283. };
  72284. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72285. var renderPipeline = this._renderPipelines[renderPipelineName];
  72286. if (!renderPipeline) {
  72287. return;
  72288. }
  72289. renderPipeline._disableEffect(renderEffectName, cameras);
  72290. };
  72291. PostProcessRenderPipelineManager.prototype.update = function () {
  72292. for (var renderPipelineName in this._renderPipelines) {
  72293. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72294. var pipeline = this._renderPipelines[renderPipelineName];
  72295. if (!pipeline.isSupported) {
  72296. pipeline.dispose();
  72297. delete this._renderPipelines[renderPipelineName];
  72298. }
  72299. else {
  72300. pipeline._update();
  72301. }
  72302. }
  72303. }
  72304. };
  72305. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72306. for (var renderPipelineName in this._renderPipelines) {
  72307. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72308. var pipeline = this._renderPipelines[renderPipelineName];
  72309. pipeline._rebuild();
  72310. }
  72311. }
  72312. };
  72313. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72314. for (var renderPipelineName in this._renderPipelines) {
  72315. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72316. var pipeline = this._renderPipelines[renderPipelineName];
  72317. pipeline.dispose();
  72318. }
  72319. }
  72320. };
  72321. return PostProcessRenderPipelineManager;
  72322. }());
  72323. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72324. })(BABYLON || (BABYLON = {}));
  72325. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72326. var BABYLON;
  72327. (function (BABYLON) {
  72328. /**
  72329. * This represents a set of one or more post processes in Babylon.
  72330. * A post process can be used to apply a shader to a texture after it is rendered.
  72331. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72332. */
  72333. var PostProcessRenderEffect = /** @class */ (function () {
  72334. /**
  72335. * Instantiates a post process render effect.
  72336. * A post process can be used to apply a shader to a texture after it is rendered.
  72337. * @param engine The engine the effect is tied to
  72338. * @param name The name of the effect
  72339. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72340. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72341. */
  72342. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72343. this._name = name;
  72344. this._singleInstance = singleInstance || true;
  72345. this._getPostProcesses = getPostProcesses;
  72346. this._cameras = {};
  72347. this._indicesForCamera = {};
  72348. this._postProcesses = {};
  72349. }
  72350. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72351. /**
  72352. * Checks if all the post processes in the effect are supported.
  72353. */
  72354. get: function () {
  72355. for (var index in this._postProcesses) {
  72356. if (this._postProcesses.hasOwnProperty(index)) {
  72357. var pps = this._postProcesses[index];
  72358. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72359. if (!pps[ppIndex].isSupported) {
  72360. return false;
  72361. }
  72362. }
  72363. }
  72364. }
  72365. return true;
  72366. },
  72367. enumerable: true,
  72368. configurable: true
  72369. });
  72370. /**
  72371. * Updates the current state of the effect
  72372. */
  72373. PostProcessRenderEffect.prototype._update = function () {
  72374. };
  72375. /**
  72376. * Attaches the effect on cameras
  72377. * @param cameras The camera to attach to.
  72378. */
  72379. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72380. var _this = this;
  72381. var cameraKey;
  72382. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72383. if (!cams) {
  72384. return;
  72385. }
  72386. for (var i = 0; i < cams.length; i++) {
  72387. var camera = cams[i];
  72388. var cameraName = camera.name;
  72389. if (this._singleInstance) {
  72390. cameraKey = 0;
  72391. }
  72392. else {
  72393. cameraKey = cameraName;
  72394. }
  72395. if (!this._postProcesses[cameraKey]) {
  72396. var postProcess = this._getPostProcesses();
  72397. if (postProcess) {
  72398. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72399. }
  72400. }
  72401. if (!this._indicesForCamera[cameraName]) {
  72402. this._indicesForCamera[cameraName] = [];
  72403. }
  72404. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72405. var index = camera.attachPostProcess(postProcess);
  72406. _this._indicesForCamera[cameraName].push(index);
  72407. });
  72408. if (!this._cameras[cameraName]) {
  72409. this._cameras[cameraName] = camera;
  72410. }
  72411. }
  72412. };
  72413. /**
  72414. * Detatches the effect on cameras
  72415. * @param cameras The camera to detatch from.
  72416. */
  72417. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72418. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72419. if (!cams) {
  72420. return;
  72421. }
  72422. for (var i = 0; i < cams.length; i++) {
  72423. var camera = cams[i];
  72424. var cameraName = camera.name;
  72425. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72426. camera.detachPostProcess(postProcess);
  72427. });
  72428. if (this._cameras[cameraName]) {
  72429. //this._indicesForCamera.splice(index, 1);
  72430. this._cameras[cameraName] = null;
  72431. }
  72432. }
  72433. };
  72434. /**
  72435. * Enables the effect on given cameras
  72436. * @param cameras The camera to enable.
  72437. */
  72438. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72439. var _this = this;
  72440. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72441. if (!cams) {
  72442. return;
  72443. }
  72444. for (var i = 0; i < cams.length; i++) {
  72445. var camera = cams[i];
  72446. var cameraName = camera.name;
  72447. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72448. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72449. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72450. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72451. });
  72452. }
  72453. }
  72454. }
  72455. };
  72456. /**
  72457. * Disables the effect on the given cameras
  72458. * @param cameras The camera to disable.
  72459. */
  72460. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72461. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72462. if (!cams) {
  72463. return;
  72464. }
  72465. for (var i = 0; i < cams.length; i++) {
  72466. var camera = cams[i];
  72467. var cameraName = camera.name;
  72468. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72469. camera.detachPostProcess(postProcess);
  72470. });
  72471. }
  72472. };
  72473. /**
  72474. * Gets a list of the post processes contained in the effect.
  72475. * @param camera The camera to get the post processes on.
  72476. * @returns The list of the post processes in the effect.
  72477. */
  72478. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72479. if (this._singleInstance) {
  72480. return this._postProcesses[0];
  72481. }
  72482. else {
  72483. if (!camera) {
  72484. return null;
  72485. }
  72486. return this._postProcesses[camera.name];
  72487. }
  72488. };
  72489. return PostProcessRenderEffect;
  72490. }());
  72491. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72492. })(BABYLON || (BABYLON = {}));
  72493. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72494. var BABYLON;
  72495. (function (BABYLON) {
  72496. var PostProcessRenderPipeline = /** @class */ (function () {
  72497. function PostProcessRenderPipeline(engine, name) {
  72498. this.engine = engine;
  72499. this._name = name;
  72500. this._renderEffects = {};
  72501. this._renderEffectsForIsolatedPass = new Array();
  72502. this._cameras = [];
  72503. }
  72504. PostProcessRenderPipeline.prototype.getClassName = function () {
  72505. return "PostProcessRenderPipeline";
  72506. };
  72507. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72508. get: function () {
  72509. for (var renderEffectName in this._renderEffects) {
  72510. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72511. if (!this._renderEffects[renderEffectName].isSupported) {
  72512. return false;
  72513. }
  72514. }
  72515. }
  72516. return true;
  72517. },
  72518. enumerable: true,
  72519. configurable: true
  72520. });
  72521. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72522. this._renderEffects[renderEffect._name] = renderEffect;
  72523. };
  72524. // private
  72525. PostProcessRenderPipeline.prototype._rebuild = function () {
  72526. };
  72527. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72528. var renderEffects = this._renderEffects[renderEffectName];
  72529. if (!renderEffects) {
  72530. return;
  72531. }
  72532. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72533. };
  72534. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72535. var renderEffects = this._renderEffects[renderEffectName];
  72536. if (!renderEffects) {
  72537. return;
  72538. }
  72539. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72540. };
  72541. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72542. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72543. if (!cams) {
  72544. return;
  72545. }
  72546. var indicesToDelete = [];
  72547. var i;
  72548. for (i = 0; i < cams.length; i++) {
  72549. var camera = cams[i];
  72550. var cameraName = camera.name;
  72551. if (this._cameras.indexOf(camera) === -1) {
  72552. this._cameras[cameraName] = camera;
  72553. }
  72554. else if (unique) {
  72555. indicesToDelete.push(i);
  72556. }
  72557. }
  72558. for (i = 0; i < indicesToDelete.length; i++) {
  72559. cameras.splice(indicesToDelete[i], 1);
  72560. }
  72561. for (var renderEffectName in this._renderEffects) {
  72562. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72563. this._renderEffects[renderEffectName]._attachCameras(cams);
  72564. }
  72565. }
  72566. };
  72567. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72568. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72569. if (!cams) {
  72570. return;
  72571. }
  72572. for (var renderEffectName in this._renderEffects) {
  72573. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72574. this._renderEffects[renderEffectName]._detachCameras(cams);
  72575. }
  72576. }
  72577. for (var i = 0; i < cams.length; i++) {
  72578. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72579. }
  72580. };
  72581. PostProcessRenderPipeline.prototype._update = function () {
  72582. for (var renderEffectName in this._renderEffects) {
  72583. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72584. this._renderEffects[renderEffectName]._update();
  72585. }
  72586. }
  72587. for (var i = 0; i < this._cameras.length; i++) {
  72588. var cameraName = this._cameras[i].name;
  72589. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72590. this._renderEffectsForIsolatedPass[cameraName]._update();
  72591. }
  72592. }
  72593. };
  72594. PostProcessRenderPipeline.prototype._reset = function () {
  72595. this._renderEffects = {};
  72596. this._renderEffectsForIsolatedPass = new Array();
  72597. };
  72598. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72599. // 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)
  72600. var effectKeys = Object.keys(this._renderEffects);
  72601. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72602. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72603. if (postProcesses) {
  72604. postProcesses[0].samples = sampleCount;
  72605. return true;
  72606. }
  72607. }
  72608. return false;
  72609. };
  72610. PostProcessRenderPipeline.prototype.dispose = function () {
  72611. // Must be implemented by children
  72612. };
  72613. __decorate([
  72614. BABYLON.serialize()
  72615. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72616. return PostProcessRenderPipeline;
  72617. }());
  72618. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72619. })(BABYLON || (BABYLON = {}));
  72620. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72621. var BABYLON;
  72622. (function (BABYLON) {
  72623. /**
  72624. * This represents a depth renderer in Babylon.
  72625. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72626. */
  72627. var DepthRenderer = /** @class */ (function () {
  72628. /**
  72629. * Instantiates a depth renderer
  72630. * @param scene The scene the renderer belongs to
  72631. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72632. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72633. */
  72634. function DepthRenderer(scene, type, camera) {
  72635. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72636. if (camera === void 0) { camera = null; }
  72637. var _this = this;
  72638. this._scene = scene;
  72639. this._camera = camera;
  72640. var engine = scene.getEngine();
  72641. // Render target
  72642. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72643. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72644. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72645. this._depthMap.refreshRate = 1;
  72646. this._depthMap.renderParticles = false;
  72647. this._depthMap.renderList = null;
  72648. // Camera to get depth map from to support multiple concurrent cameras
  72649. this._depthMap.activeCamera = this._camera;
  72650. this._depthMap.ignoreCameraViewport = true;
  72651. this._depthMap.useCameraPostProcesses = false;
  72652. // set default depth value to 1.0 (far away)
  72653. this._depthMap.onClearObservable.add(function (engine) {
  72654. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72655. });
  72656. // Custom render function
  72657. var renderSubMesh = function (subMesh) {
  72658. var mesh = subMesh.getRenderingMesh();
  72659. var scene = _this._scene;
  72660. var engine = scene.getEngine();
  72661. var material = subMesh.getMaterial();
  72662. if (!material) {
  72663. return;
  72664. }
  72665. // Culling and reverse (right handed system)
  72666. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72667. // Managing instances
  72668. var batch = mesh._getInstancesRenderList(subMesh._id);
  72669. if (batch.mustReturn) {
  72670. return;
  72671. }
  72672. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72673. var camera = _this._camera || scene.activeCamera;
  72674. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72675. engine.enableEffect(_this._effect);
  72676. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72677. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72678. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72679. // Alpha test
  72680. if (material && material.needAlphaTesting()) {
  72681. var alphaTexture = material.getAlphaTestTexture();
  72682. if (alphaTexture) {
  72683. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72684. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72685. }
  72686. }
  72687. // Bones
  72688. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72689. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72690. }
  72691. // Draw
  72692. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72693. }
  72694. };
  72695. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72696. var index;
  72697. if (depthOnlySubMeshes.length) {
  72698. engine.setColorWrite(false);
  72699. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72700. renderSubMesh(depthOnlySubMeshes.data[index]);
  72701. }
  72702. engine.setColorWrite(true);
  72703. }
  72704. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72705. renderSubMesh(opaqueSubMeshes.data[index]);
  72706. }
  72707. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72708. renderSubMesh(alphaTestSubMeshes.data[index]);
  72709. }
  72710. };
  72711. }
  72712. /**
  72713. * Creates the depth rendering effect and checks if the effect is ready.
  72714. * @param subMesh The submesh to be used to render the depth map of
  72715. * @param useInstances If multiple world instances should be used
  72716. * @returns if the depth renderer is ready to render the depth map
  72717. */
  72718. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72719. var material = subMesh.getMaterial();
  72720. if (material.disableDepthWrite) {
  72721. return false;
  72722. }
  72723. var defines = [];
  72724. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72725. var mesh = subMesh.getMesh();
  72726. // Alpha test
  72727. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72728. defines.push("#define ALPHATEST");
  72729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72730. attribs.push(BABYLON.VertexBuffer.UVKind);
  72731. defines.push("#define UV1");
  72732. }
  72733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72734. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72735. defines.push("#define UV2");
  72736. }
  72737. }
  72738. // Bones
  72739. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72740. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72741. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72742. if (mesh.numBoneInfluencers > 4) {
  72743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72745. }
  72746. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72747. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72748. }
  72749. else {
  72750. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72751. }
  72752. // Instances
  72753. if (useInstances) {
  72754. defines.push("#define INSTANCES");
  72755. attribs.push("world0");
  72756. attribs.push("world1");
  72757. attribs.push("world2");
  72758. attribs.push("world3");
  72759. }
  72760. // Get correct effect
  72761. var join = defines.join("\n");
  72762. if (this._cachedDefines !== join) {
  72763. this._cachedDefines = join;
  72764. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72765. }
  72766. return this._effect.isReady();
  72767. };
  72768. /**
  72769. * Gets the texture which the depth map will be written to.
  72770. * @returns The depth map texture
  72771. */
  72772. DepthRenderer.prototype.getDepthMap = function () {
  72773. return this._depthMap;
  72774. };
  72775. /**
  72776. * Disposes of the depth renderer.
  72777. */
  72778. DepthRenderer.prototype.dispose = function () {
  72779. this._depthMap.dispose();
  72780. };
  72781. return DepthRenderer;
  72782. }());
  72783. BABYLON.DepthRenderer = DepthRenderer;
  72784. })(BABYLON || (BABYLON = {}));
  72785. //# sourceMappingURL=babylon.depthRenderer.js.map
  72786. var BABYLON;
  72787. (function (BABYLON) {
  72788. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72789. __extends(SSAORenderingPipeline, _super);
  72790. /**
  72791. * @constructor
  72792. * @param {string} name - The rendering pipeline name
  72793. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72794. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  72795. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72796. */
  72797. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72798. var _this = _super.call(this, scene.getEngine(), name) || this;
  72799. // Members
  72800. /**
  72801. * The PassPostProcess id in the pipeline that contains the original scene color
  72802. */
  72803. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72804. /**
  72805. * The SSAO PostProcess id in the pipeline
  72806. */
  72807. _this.SSAORenderEffect = "SSAORenderEffect";
  72808. /**
  72809. * The horizontal blur PostProcess id in the pipeline
  72810. */
  72811. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72812. /**
  72813. * The vertical blur PostProcess id in the pipeline
  72814. */
  72815. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72816. /**
  72817. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72818. */
  72819. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72820. /**
  72821. * The output strength of the SSAO post-process. Default value is 1.0.
  72822. */
  72823. _this.totalStrength = 1.0;
  72824. /**
  72825. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72826. */
  72827. _this.radius = 0.0001;
  72828. /**
  72829. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72830. * Must not be equal to fallOff and superior to fallOff.
  72831. * Default value is 0.975
  72832. */
  72833. _this.area = 0.0075;
  72834. /**
  72835. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72836. * Must not be equal to area and inferior to area.
  72837. * Default value is 0.0
  72838. */
  72839. _this.fallOff = 0.000001;
  72840. /**
  72841. * The base color of the SSAO post-process
  72842. * The final result is "base + ssao" between [0, 1]
  72843. */
  72844. _this.base = 0.5;
  72845. _this._firstUpdate = true;
  72846. _this._scene = scene;
  72847. // Set up assets
  72848. _this._createRandomTexture();
  72849. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72850. var ssaoRatio = ratio.ssaoRatio || ratio;
  72851. var combineRatio = ratio.combineRatio || ratio;
  72852. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72853. _this._createSSAOPostProcess(ssaoRatio);
  72854. _this._createBlurPostProcess(ssaoRatio);
  72855. _this._createSSAOCombinePostProcess(combineRatio);
  72856. // Set up pipeline
  72857. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72858. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72859. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72860. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72861. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72862. // Finish
  72863. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72864. if (cameras)
  72865. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72866. return _this;
  72867. }
  72868. // Public Methods
  72869. /**
  72870. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72871. */
  72872. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72873. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72874. for (var i = 0; i < this._scene.cameras.length; i++) {
  72875. var camera = this._scene.cameras[i];
  72876. this._originalColorPostProcess.dispose(camera);
  72877. this._ssaoPostProcess.dispose(camera);
  72878. this._blurHPostProcess.dispose(camera);
  72879. this._blurVPostProcess.dispose(camera);
  72880. this._ssaoCombinePostProcess.dispose(camera);
  72881. }
  72882. this._randomTexture.dispose();
  72883. if (disableDepthRender)
  72884. this._scene.disableDepthRenderer();
  72885. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72886. _super.prototype.dispose.call(this);
  72887. };
  72888. // Private Methods
  72889. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72890. var _this = this;
  72891. var size = 16;
  72892. 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);
  72893. 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);
  72894. this._blurHPostProcess.onActivateObservable.add(function () {
  72895. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72896. _this._blurHPostProcess.kernel = size * dw;
  72897. });
  72898. this._blurVPostProcess.onActivateObservable.add(function () {
  72899. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72900. _this._blurVPostProcess.kernel = size * dw;
  72901. });
  72902. };
  72903. SSAORenderingPipeline.prototype._rebuild = function () {
  72904. this._firstUpdate = true;
  72905. _super.prototype._rebuild.call(this);
  72906. };
  72907. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72908. var _this = this;
  72909. var numSamples = 16;
  72910. var sampleSphere = [
  72911. 0.5381, 0.1856, -0.4319,
  72912. 0.1379, 0.2486, 0.4430,
  72913. 0.3371, 0.5679, -0.0057,
  72914. -0.6999, -0.0451, -0.0019,
  72915. 0.0689, -0.1598, -0.8547,
  72916. 0.0560, 0.0069, -0.1843,
  72917. -0.0146, 0.1402, 0.0762,
  72918. 0.0100, -0.1924, -0.0344,
  72919. -0.3577, -0.5301, -0.4358,
  72920. -0.3169, 0.1063, 0.0158,
  72921. 0.0103, -0.5869, 0.0046,
  72922. -0.0897, -0.4940, 0.3287,
  72923. 0.7119, -0.0154, -0.0918,
  72924. -0.0533, 0.0596, -0.5411,
  72925. 0.0352, -0.0631, 0.5460,
  72926. -0.4776, 0.2847, -0.0271
  72927. ];
  72928. var samplesFactor = 1.0 / numSamples;
  72929. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72930. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72931. "area", "fallOff", "base", "range", "viewport"
  72932. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72933. this._ssaoPostProcess.onApply = function (effect) {
  72934. if (_this._firstUpdate) {
  72935. effect.setArray3("sampleSphere", sampleSphere);
  72936. effect.setFloat("samplesFactor", samplesFactor);
  72937. effect.setFloat("randTextureTiles", 4.0);
  72938. }
  72939. effect.setFloat("totalStrength", _this.totalStrength);
  72940. effect.setFloat("radius", _this.radius);
  72941. effect.setFloat("area", _this.area);
  72942. effect.setFloat("fallOff", _this.fallOff);
  72943. effect.setFloat("base", _this.base);
  72944. effect.setTexture("textureSampler", _this._depthTexture);
  72945. effect.setTexture("randomSampler", _this._randomTexture);
  72946. };
  72947. };
  72948. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72949. var _this = this;
  72950. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72951. this._ssaoCombinePostProcess.onApply = function (effect) {
  72952. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72953. };
  72954. };
  72955. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72956. var size = 512;
  72957. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72958. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72959. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72960. var context = this._randomTexture.getContext();
  72961. var rand = function (min, max) {
  72962. return Math.random() * (max - min) + min;
  72963. };
  72964. var randVector = BABYLON.Vector3.Zero();
  72965. for (var x = 0; x < size; x++) {
  72966. for (var y = 0; y < size; y++) {
  72967. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72968. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72969. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72970. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72971. context.fillRect(x, y, 1, 1);
  72972. }
  72973. }
  72974. this._randomTexture.update(false);
  72975. };
  72976. __decorate([
  72977. BABYLON.serialize()
  72978. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72979. __decorate([
  72980. BABYLON.serialize()
  72981. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72982. __decorate([
  72983. BABYLON.serialize()
  72984. ], SSAORenderingPipeline.prototype, "area", void 0);
  72985. __decorate([
  72986. BABYLON.serialize()
  72987. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72988. __decorate([
  72989. BABYLON.serialize()
  72990. ], SSAORenderingPipeline.prototype, "base", void 0);
  72991. return SSAORenderingPipeline;
  72992. }(BABYLON.PostProcessRenderPipeline));
  72993. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72994. })(BABYLON || (BABYLON = {}));
  72995. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72996. var BABYLON;
  72997. (function (BABYLON) {
  72998. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72999. __extends(SSAO2RenderingPipeline, _super);
  73000. /**
  73001. * @constructor
  73002. * @param {string} name - The rendering pipeline name
  73003. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73004. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  73005. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73006. */
  73007. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73008. var _this = _super.call(this, scene.getEngine(), name) || this;
  73009. // Members
  73010. /**
  73011. * The PassPostProcess id in the pipeline that contains the original scene color
  73012. */
  73013. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73014. /**
  73015. * The SSAO PostProcess id in the pipeline
  73016. */
  73017. _this.SSAORenderEffect = "SSAORenderEffect";
  73018. /**
  73019. * The horizontal blur PostProcess id in the pipeline
  73020. */
  73021. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73022. /**
  73023. * The vertical blur PostProcess id in the pipeline
  73024. */
  73025. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73026. /**
  73027. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73028. */
  73029. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73030. /**
  73031. * The output strength of the SSAO post-process. Default value is 1.0.
  73032. */
  73033. _this.totalStrength = 1.0;
  73034. /**
  73035. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73036. */
  73037. _this.maxZ = 100.0;
  73038. /**
  73039. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73040. */
  73041. _this.minZAspect = 0.2;
  73042. /**
  73043. * Number of samples used for the SSAO calculations. Default value is 8
  73044. */
  73045. _this._samples = 8;
  73046. /**
  73047. * Are we using bilateral blur ?
  73048. */
  73049. _this._expensiveBlur = true;
  73050. /**
  73051. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73052. */
  73053. _this.radius = 2.0;
  73054. /**
  73055. * The base color of the SSAO post-process
  73056. * The final result is "base + ssao" between [0, 1]
  73057. */
  73058. _this.base = 0.1;
  73059. _this._firstUpdate = true;
  73060. _this._scene = scene;
  73061. if (!_this.isSupported) {
  73062. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73063. return _this;
  73064. }
  73065. var ssaoRatio = ratio.ssaoRatio || ratio;
  73066. var blurRatio = ratio.blurRatio || ratio;
  73067. // Set up assets
  73068. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73069. _this._createRandomTexture();
  73070. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73071. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73072. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73073. _this._createSSAOPostProcess(1.0);
  73074. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73075. _this._createSSAOCombinePostProcess(blurRatio);
  73076. // Set up pipeline
  73077. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73078. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73081. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73082. // Finish
  73083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73084. if (cameras)
  73085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73086. return _this;
  73087. }
  73088. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73089. get: function () {
  73090. return this._samples;
  73091. },
  73092. set: function (n) {
  73093. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73094. this._samples = n;
  73095. this._sampleSphere = this._generateHemisphere();
  73096. this._firstUpdate = true;
  73097. },
  73098. enumerable: true,
  73099. configurable: true
  73100. });
  73101. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73102. get: function () {
  73103. return this._expensiveBlur;
  73104. },
  73105. set: function (b) {
  73106. 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"]);
  73107. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73108. this._expensiveBlur = b;
  73109. this._firstUpdate = true;
  73110. },
  73111. enumerable: true,
  73112. configurable: true
  73113. });
  73114. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73115. /**
  73116. * Support test.
  73117. */
  73118. get: function () {
  73119. var engine = BABYLON.Engine.LastCreatedEngine;
  73120. if (!engine) {
  73121. return false;
  73122. }
  73123. return engine.getCaps().drawBuffersExtension;
  73124. },
  73125. enumerable: true,
  73126. configurable: true
  73127. });
  73128. // Public Methods
  73129. /**
  73130. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73131. */
  73132. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73133. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73134. for (var i = 0; i < this._scene.cameras.length; i++) {
  73135. var camera = this._scene.cameras[i];
  73136. this._originalColorPostProcess.dispose(camera);
  73137. this._ssaoPostProcess.dispose(camera);
  73138. this._blurHPostProcess.dispose(camera);
  73139. this._blurVPostProcess.dispose(camera);
  73140. this._ssaoCombinePostProcess.dispose(camera);
  73141. }
  73142. this._randomTexture.dispose();
  73143. if (disableGeometryBufferRenderer)
  73144. this._scene.disableGeometryBufferRenderer();
  73145. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73146. _super.prototype.dispose.call(this);
  73147. };
  73148. // Private Methods
  73149. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73150. var _this = this;
  73151. this._samplerOffsets = [];
  73152. var expensive = this.expensiveBlur;
  73153. for (var i = -8; i < 8; i++) {
  73154. this._samplerOffsets.push(i * 2 + 0.5);
  73155. }
  73156. 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");
  73157. this._blurHPostProcess.onApply = function (effect) {
  73158. if (!_this._scene.activeCamera) {
  73159. return;
  73160. }
  73161. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73162. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73163. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73164. effect.setFloat("radius", _this.radius);
  73165. effect.setTexture("depthSampler", _this._depthTexture);
  73166. if (_this._firstUpdate) {
  73167. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73168. }
  73169. };
  73170. 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");
  73171. this._blurVPostProcess.onApply = function (effect) {
  73172. if (!_this._scene.activeCamera) {
  73173. return;
  73174. }
  73175. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73176. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73177. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73178. effect.setFloat("radius", _this.radius);
  73179. effect.setTexture("depthSampler", _this._depthTexture);
  73180. if (_this._firstUpdate) {
  73181. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73182. _this._firstUpdate = false;
  73183. }
  73184. };
  73185. };
  73186. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73187. this._firstUpdate = true;
  73188. _super.prototype._rebuild.call(this);
  73189. };
  73190. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73191. var numSamples = this.samples;
  73192. var result = [];
  73193. var vector, scale;
  73194. var rand = function (min, max) {
  73195. return Math.random() * (max - min) + min;
  73196. };
  73197. var i = 0;
  73198. while (i < numSamples) {
  73199. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73200. vector.normalize();
  73201. scale = i / numSamples;
  73202. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73203. vector.scaleInPlace(scale);
  73204. result.push(vector.x, vector.y, vector.z);
  73205. i++;
  73206. }
  73207. return result;
  73208. };
  73209. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73210. var _this = this;
  73211. var numSamples = this.samples;
  73212. this._sampleSphere = this._generateHemisphere();
  73213. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73214. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73215. "base", "range", "projection", "near", "far", "texelSize",
  73216. "xViewport", "yViewport", "maxZ", "minZAspect"
  73217. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73218. this._ssaoPostProcess.onApply = function (effect) {
  73219. if (_this._firstUpdate) {
  73220. effect.setArray3("sampleSphere", _this._sampleSphere);
  73221. effect.setFloat("randTextureTiles", 4.0);
  73222. }
  73223. if (!_this._scene.activeCamera) {
  73224. return;
  73225. }
  73226. effect.setFloat("samplesFactor", 1 / _this.samples);
  73227. effect.setFloat("totalStrength", _this.totalStrength);
  73228. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73229. effect.setFloat("radius", _this.radius);
  73230. effect.setFloat("maxZ", _this.maxZ);
  73231. effect.setFloat("minZAspect", _this.minZAspect);
  73232. effect.setFloat("base", _this.base);
  73233. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73234. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73235. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73236. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73237. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73238. effect.setTexture("textureSampler", _this._depthTexture);
  73239. effect.setTexture("normalSampler", _this._normalTexture);
  73240. effect.setTexture("randomSampler", _this._randomTexture);
  73241. };
  73242. };
  73243. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73244. var _this = this;
  73245. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73246. this._ssaoCombinePostProcess.onApply = function (effect) {
  73247. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73248. };
  73249. };
  73250. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73251. var size = 512;
  73252. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73253. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73254. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73255. var context = this._randomTexture.getContext();
  73256. var rand = function (min, max) {
  73257. return Math.random() * (max - min) + min;
  73258. };
  73259. var randVector = BABYLON.Vector3.Zero();
  73260. for (var x = 0; x < size; x++) {
  73261. for (var y = 0; y < size; y++) {
  73262. randVector.x = rand(0.0, 1.0);
  73263. randVector.y = rand(0.0, 1.0);
  73264. randVector.z = 0.0;
  73265. randVector.normalize();
  73266. randVector.scaleInPlace(255);
  73267. randVector.x = Math.floor(randVector.x);
  73268. randVector.y = Math.floor(randVector.y);
  73269. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73270. context.fillRect(x, y, 1, 1);
  73271. }
  73272. }
  73273. this._randomTexture.update(false);
  73274. };
  73275. __decorate([
  73276. BABYLON.serialize()
  73277. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73278. __decorate([
  73279. BABYLON.serialize()
  73280. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73281. __decorate([
  73282. BABYLON.serialize()
  73283. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73284. __decorate([
  73285. BABYLON.serialize("samples")
  73286. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73287. __decorate([
  73288. BABYLON.serialize("expensiveBlur")
  73289. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73290. __decorate([
  73291. BABYLON.serialize()
  73292. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73293. __decorate([
  73294. BABYLON.serialize()
  73295. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73296. return SSAO2RenderingPipeline;
  73297. }(BABYLON.PostProcessRenderPipeline));
  73298. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73299. })(BABYLON || (BABYLON = {}));
  73300. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73301. // BABYLON.JS Chromatic Aberration GLSL Shader
  73302. // Author: Olivier Guyot
  73303. // Separates very slightly R, G and B colors on the edges of the screen
  73304. // Inspired by Francois Tarlier & Martins Upitis
  73305. var BABYLON;
  73306. (function (BABYLON) {
  73307. var LensRenderingPipeline = /** @class */ (function (_super) {
  73308. __extends(LensRenderingPipeline, _super);
  73309. /**
  73310. * @constructor
  73311. *
  73312. * Effect parameters are as follow:
  73313. * {
  73314. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73315. * edge_blur: number; // from 0 to x (1 for realism)
  73316. * distortion: number; // from 0 to x (1 for realism)
  73317. * grain_amount: number; // from 0 to 1
  73318. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73319. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73320. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73321. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73322. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73323. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73324. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73325. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73326. * }
  73327. * Note: if an effect parameter is unset, effect is disabled
  73328. *
  73329. * @param {string} name - The rendering pipeline name
  73330. * @param {object} parameters - An object containing all parameters (see above)
  73331. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73332. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  73333. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73334. */
  73335. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73336. if (ratio === void 0) { ratio = 1.0; }
  73337. var _this = _super.call(this, scene.getEngine(), name) || this;
  73338. // Lens effects can be of the following:
  73339. // - chromatic aberration (slight shift of RGB colors)
  73340. // - blur on the edge of the lens
  73341. // - lens distortion
  73342. // - depth-of-field blur & highlights enhancing
  73343. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73344. // - grain effect (noise or custom texture)
  73345. // Two additional texture samplers are needed:
  73346. // - depth map (for depth-of-field)
  73347. // - grain texture
  73348. /**
  73349. * The chromatic aberration PostProcess id in the pipeline
  73350. */
  73351. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73352. /**
  73353. * The highlights enhancing PostProcess id in the pipeline
  73354. */
  73355. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73356. /**
  73357. * The depth-of-field PostProcess id in the pipeline
  73358. */
  73359. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73360. _this._scene = scene;
  73361. // Fetch texture samplers
  73362. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73363. if (parameters.grain_texture) {
  73364. _this._grainTexture = parameters.grain_texture;
  73365. }
  73366. else {
  73367. _this._createGrainTexture();
  73368. }
  73369. // save parameters
  73370. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73371. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73372. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73373. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73374. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73375. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73376. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73377. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73378. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73379. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73380. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73381. // Create effects
  73382. _this._createChromaticAberrationPostProcess(ratio);
  73383. _this._createHighlightsPostProcess(ratio);
  73384. _this._createDepthOfFieldPostProcess(ratio / 4);
  73385. // Set up pipeline
  73386. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73389. if (_this._highlightsGain === -1) {
  73390. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73391. }
  73392. // Finish
  73393. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73394. if (cameras) {
  73395. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73396. }
  73397. return _this;
  73398. }
  73399. // public methods (self explanatory)
  73400. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73401. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73402. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73403. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73404. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73405. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73406. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73407. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73408. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73409. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73410. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73411. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73412. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73413. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73414. };
  73415. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73416. this._highlightsPostProcess.updateEffect();
  73417. };
  73418. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73419. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73420. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73421. this._highlightsGain = amount;
  73422. };
  73423. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73424. if (this._highlightsGain === -1) {
  73425. this._highlightsGain = 1.0;
  73426. }
  73427. this._highlightsThreshold = amount;
  73428. };
  73429. LensRenderingPipeline.prototype.disableHighlights = function () {
  73430. this._highlightsGain = -1;
  73431. };
  73432. /**
  73433. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73434. */
  73435. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73436. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73437. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73438. this._chromaticAberrationPostProcess = null;
  73439. this._highlightsPostProcess = null;
  73440. this._depthOfFieldPostProcess = null;
  73441. this._grainTexture.dispose();
  73442. if (disableDepthRender)
  73443. this._scene.disableDepthRenderer();
  73444. };
  73445. // colors shifting and distortion
  73446. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73447. var _this = this;
  73448. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73449. [], // samplers
  73450. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73451. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73452. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73453. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73454. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73455. effect.setFloat('radialIntensity', 1);
  73456. effect.setFloat2('direction', 17, 17);
  73457. effect.setFloat2('centerPosition', 0.5, 0.5);
  73458. };
  73459. };
  73460. // highlights enhancing
  73461. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73462. var _this = this;
  73463. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73464. [], // samplers
  73465. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73466. this._highlightsPostProcess.onApply = function (effect) {
  73467. effect.setFloat('gain', _this._highlightsGain);
  73468. effect.setFloat('threshold', _this._highlightsThreshold);
  73469. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73470. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73471. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73472. };
  73473. };
  73474. // colors shifting and distortion
  73475. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73476. var _this = this;
  73477. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73478. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73479. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73480. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73481. this._depthOfFieldPostProcess.onApply = function (effect) {
  73482. effect.setTexture("depthSampler", _this._depthTexture);
  73483. effect.setTexture("grainSampler", _this._grainTexture);
  73484. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73485. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73486. effect.setFloat('grain_amount', _this._grainAmount);
  73487. effect.setBool('blur_noise', _this._blurNoise);
  73488. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73489. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73490. effect.setFloat('distortion', _this._distortion);
  73491. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73492. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73493. effect.setFloat('aperture', _this._dofAperture);
  73494. effect.setFloat('darken', _this._dofDarken);
  73495. effect.setFloat('edge_blur', _this._edgeBlur);
  73496. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73497. if (_this._scene.activeCamera) {
  73498. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73499. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73500. }
  73501. };
  73502. };
  73503. // creates a black and white random noise texture, 512x512
  73504. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73505. var size = 512;
  73506. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73507. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73508. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73509. var context = this._grainTexture.getContext();
  73510. var rand = function (min, max) {
  73511. return Math.random() * (max - min) + min;
  73512. };
  73513. var value;
  73514. for (var x = 0; x < size; x++) {
  73515. for (var y = 0; y < size; y++) {
  73516. value = Math.floor(rand(0.42, 0.58) * 255);
  73517. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73518. context.fillRect(x, y, 1, 1);
  73519. }
  73520. }
  73521. this._grainTexture.update(false);
  73522. };
  73523. return LensRenderingPipeline;
  73524. }(BABYLON.PostProcessRenderPipeline));
  73525. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73526. })(BABYLON || (BABYLON = {}));
  73527. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73528. var BABYLON;
  73529. (function (BABYLON) {
  73530. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73531. __extends(StandardRenderingPipeline, _super);
  73532. /**
  73533. * @constructor
  73534. * @param {string} name - The rendering pipeline name
  73535. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73536. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  73537. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73538. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73539. */
  73540. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73541. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73542. var _this = _super.call(this, scene.getEngine(), name) || this;
  73543. _this.downSampleX4PostProcess = null;
  73544. _this.brightPassPostProcess = null;
  73545. _this.blurHPostProcesses = [];
  73546. _this.blurVPostProcesses = [];
  73547. _this.textureAdderPostProcess = null;
  73548. _this.volumetricLightPostProcess = null;
  73549. _this.volumetricLightSmoothXPostProcess = null;
  73550. _this.volumetricLightSmoothYPostProcess = null;
  73551. _this.volumetricLightMergePostProces = null;
  73552. _this.volumetricLightFinalPostProcess = null;
  73553. _this.luminancePostProcess = null;
  73554. _this.luminanceDownSamplePostProcesses = [];
  73555. _this.hdrPostProcess = null;
  73556. _this.textureAdderFinalPostProcess = null;
  73557. _this.lensFlareFinalPostProcess = null;
  73558. _this.hdrFinalPostProcess = null;
  73559. _this.lensFlarePostProcess = null;
  73560. _this.lensFlareComposePostProcess = null;
  73561. _this.motionBlurPostProcess = null;
  73562. _this.depthOfFieldPostProcess = null;
  73563. // Values
  73564. _this.brightThreshold = 1.0;
  73565. _this.blurWidth = 512.0;
  73566. _this.horizontalBlur = false;
  73567. _this.exposure = 1.0;
  73568. _this.lensTexture = null;
  73569. _this.volumetricLightCoefficient = 0.2;
  73570. _this.volumetricLightPower = 4.0;
  73571. _this.volumetricLightBlurScale = 64.0;
  73572. _this.sourceLight = null;
  73573. _this.hdrMinimumLuminance = 1.0;
  73574. _this.hdrDecreaseRate = 0.5;
  73575. _this.hdrIncreaseRate = 0.5;
  73576. _this.lensColorTexture = null;
  73577. _this.lensFlareStrength = 20.0;
  73578. _this.lensFlareGhostDispersal = 1.4;
  73579. _this.lensFlareHaloWidth = 0.7;
  73580. _this.lensFlareDistortionStrength = 16.0;
  73581. _this.lensStarTexture = null;
  73582. _this.lensFlareDirtTexture = null;
  73583. _this.depthOfFieldDistance = 10.0;
  73584. _this.depthOfFieldBlurWidth = 64.0;
  73585. _this.motionStrength = 1.0;
  73586. // IAnimatable
  73587. _this.animations = [];
  73588. _this._currentDepthOfFieldSource = null;
  73589. _this._hdrCurrentLuminance = 1.0;
  73590. // Getters and setters
  73591. _this._bloomEnabled = true;
  73592. _this._depthOfFieldEnabled = false;
  73593. _this._vlsEnabled = false;
  73594. _this._lensFlareEnabled = false;
  73595. _this._hdrEnabled = false;
  73596. _this._motionBlurEnabled = false;
  73597. _this._motionBlurSamples = 64.0;
  73598. _this._volumetricLightStepsCount = 50.0;
  73599. _this._cameras = cameras || [];
  73600. // Initialize
  73601. _this._scene = scene;
  73602. _this._basePostProcess = originalPostProcess;
  73603. _this._ratio = ratio;
  73604. // Misc
  73605. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73606. // Finish
  73607. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73608. _this._buildPipeline();
  73609. return _this;
  73610. }
  73611. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73612. get: function () {
  73613. return this._bloomEnabled;
  73614. },
  73615. set: function (enabled) {
  73616. if (this._bloomEnabled === enabled) {
  73617. return;
  73618. }
  73619. this._bloomEnabled = enabled;
  73620. this._buildPipeline();
  73621. },
  73622. enumerable: true,
  73623. configurable: true
  73624. });
  73625. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73626. get: function () {
  73627. return this._depthOfFieldEnabled;
  73628. },
  73629. set: function (enabled) {
  73630. if (this._depthOfFieldEnabled === enabled) {
  73631. return;
  73632. }
  73633. this._depthOfFieldEnabled = enabled;
  73634. this._buildPipeline();
  73635. },
  73636. enumerable: true,
  73637. configurable: true
  73638. });
  73639. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73640. get: function () {
  73641. return this._lensFlareEnabled;
  73642. },
  73643. set: function (enabled) {
  73644. if (this._lensFlareEnabled === enabled) {
  73645. return;
  73646. }
  73647. this._lensFlareEnabled = enabled;
  73648. this._buildPipeline();
  73649. },
  73650. enumerable: true,
  73651. configurable: true
  73652. });
  73653. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73654. get: function () {
  73655. return this._hdrEnabled;
  73656. },
  73657. set: function (enabled) {
  73658. if (this._hdrEnabled === enabled) {
  73659. return;
  73660. }
  73661. this._hdrEnabled = enabled;
  73662. this._buildPipeline();
  73663. },
  73664. enumerable: true,
  73665. configurable: true
  73666. });
  73667. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73668. get: function () {
  73669. return this._vlsEnabled;
  73670. },
  73671. set: function (enabled) {
  73672. if (this._vlsEnabled === enabled) {
  73673. return;
  73674. }
  73675. if (enabled) {
  73676. var geometry = this._scene.enableGeometryBufferRenderer();
  73677. if (!geometry) {
  73678. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73679. return;
  73680. }
  73681. }
  73682. this._vlsEnabled = enabled;
  73683. this._buildPipeline();
  73684. },
  73685. enumerable: true,
  73686. configurable: true
  73687. });
  73688. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73689. get: function () {
  73690. return this._motionBlurEnabled;
  73691. },
  73692. set: function (enabled) {
  73693. if (this._motionBlurEnabled === enabled) {
  73694. return;
  73695. }
  73696. this._motionBlurEnabled = enabled;
  73697. this._buildPipeline();
  73698. },
  73699. enumerable: true,
  73700. configurable: true
  73701. });
  73702. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73703. get: function () {
  73704. return this._volumetricLightStepsCount;
  73705. },
  73706. set: function (count) {
  73707. if (this.volumetricLightPostProcess) {
  73708. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73709. }
  73710. this._volumetricLightStepsCount = count;
  73711. },
  73712. enumerable: true,
  73713. configurable: true
  73714. });
  73715. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73716. get: function () {
  73717. return this._motionBlurSamples;
  73718. },
  73719. set: function (samples) {
  73720. if (this.motionBlurPostProcess) {
  73721. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73722. }
  73723. this._motionBlurSamples = samples;
  73724. },
  73725. enumerable: true,
  73726. configurable: true
  73727. });
  73728. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73729. var _this = this;
  73730. var ratio = this._ratio;
  73731. var scene = this._scene;
  73732. this._disposePostProcesses();
  73733. this._reset();
  73734. // Create pass post-process
  73735. if (!this._basePostProcess) {
  73736. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73737. this.originalPostProcess.onApply = function (effect) {
  73738. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73739. };
  73740. }
  73741. else {
  73742. this.originalPostProcess = this._basePostProcess;
  73743. }
  73744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73745. this._currentDepthOfFieldSource = this.originalPostProcess;
  73746. if (this._vlsEnabled) {
  73747. // Create volumetric light
  73748. this._createVolumetricLightPostProcess(scene, ratio);
  73749. // Create volumetric light final post-process
  73750. 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);
  73751. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73752. }
  73753. if (this._bloomEnabled) {
  73754. // Create down sample X4 post-process
  73755. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73756. // Create bright pass post-process
  73757. this._createBrightPassPostProcess(scene, ratio / 2);
  73758. // Create gaussian blur post-processes (down sampling blurs)
  73759. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73760. // Create texture adder post-process
  73761. this._createTextureAdderPostProcess(scene, ratio);
  73762. // Create depth-of-field source post-process
  73763. 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);
  73764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73765. }
  73766. if (this._lensFlareEnabled) {
  73767. // Create lens flare post-process
  73768. this._createLensFlarePostProcess(scene, ratio);
  73769. // Create depth-of-field source post-process post lens-flare and disable it now
  73770. 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);
  73771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73772. }
  73773. if (this._hdrEnabled) {
  73774. // Create luminance
  73775. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73776. // Create HDR
  73777. this._createHdrPostProcess(scene, ratio);
  73778. // Create depth-of-field source post-process post hdr and disable it now
  73779. 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);
  73780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73781. }
  73782. if (this._depthOfFieldEnabled) {
  73783. // Create gaussian blur used by depth-of-field
  73784. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73785. // Create depth-of-field post-process
  73786. this._createDepthOfFieldPostProcess(scene, ratio);
  73787. }
  73788. if (this._motionBlurEnabled) {
  73789. // Create motion blur post-process
  73790. this._createMotionBlurPostProcess(scene, ratio);
  73791. }
  73792. if (this._cameras !== null) {
  73793. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73794. }
  73795. };
  73796. // Down Sample X4 Post-Processs
  73797. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73798. var _this = this;
  73799. var downSampleX4Offsets = new Array(32);
  73800. 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);
  73801. this.downSampleX4PostProcess.onApply = function (effect) {
  73802. var id = 0;
  73803. var width = _this.downSampleX4PostProcess.width;
  73804. var height = _this.downSampleX4PostProcess.height;
  73805. for (var i = -2; i < 2; i++) {
  73806. for (var j = -2; j < 2; j++) {
  73807. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73808. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73809. id += 2;
  73810. }
  73811. }
  73812. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73813. };
  73814. // Add to pipeline
  73815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73816. };
  73817. // Brightpass Post-Process
  73818. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73819. var _this = this;
  73820. var brightOffsets = new Array(8);
  73821. 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);
  73822. this.brightPassPostProcess.onApply = function (effect) {
  73823. var sU = (1.0 / _this.brightPassPostProcess.width);
  73824. var sV = (1.0 / _this.brightPassPostProcess.height);
  73825. brightOffsets[0] = -0.5 * sU;
  73826. brightOffsets[1] = 0.5 * sV;
  73827. brightOffsets[2] = 0.5 * sU;
  73828. brightOffsets[3] = 0.5 * sV;
  73829. brightOffsets[4] = -0.5 * sU;
  73830. brightOffsets[5] = -0.5 * sV;
  73831. brightOffsets[6] = 0.5 * sU;
  73832. brightOffsets[7] = -0.5 * sV;
  73833. effect.setArray2("dsOffsets", brightOffsets);
  73834. effect.setFloat("brightThreshold", _this.brightThreshold);
  73835. };
  73836. // Add to pipeline
  73837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73838. };
  73839. // Create blur H&V post-processes
  73840. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73841. var _this = this;
  73842. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73843. var engine = scene.getEngine();
  73844. 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);
  73845. 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);
  73846. blurX.onActivateObservable.add(function () {
  73847. var dw = blurX.width / engine.getRenderWidth();
  73848. blurX.kernel = _this[blurWidthKey] * dw;
  73849. });
  73850. blurY.onActivateObservable.add(function () {
  73851. var dw = blurY.height / engine.getRenderHeight();
  73852. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73853. });
  73854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73856. this.blurHPostProcesses.push(blurX);
  73857. this.blurVPostProcesses.push(blurY);
  73858. };
  73859. // Create texture adder post-process
  73860. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73861. var _this = this;
  73862. 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);
  73863. this.textureAdderPostProcess.onApply = function (effect) {
  73864. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73865. effect.setTexture("lensSampler", _this.lensTexture);
  73866. effect.setFloat("exposure", _this.exposure);
  73867. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73868. };
  73869. // Add to pipeline
  73870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73871. };
  73872. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73873. var _this = this;
  73874. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73875. geometryRenderer.enablePosition = true;
  73876. var geometry = geometryRenderer.getGBuffer();
  73877. // Base post-process
  73878. 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));
  73879. var depthValues = BABYLON.Vector2.Zero();
  73880. this.volumetricLightPostProcess.onApply = function (effect) {
  73881. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73882. var generator = _this.sourceLight.getShadowGenerator();
  73883. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73884. effect.setTexture("positionSampler", geometry.textures[2]);
  73885. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73886. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73887. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73888. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73889. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73890. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73891. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73892. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73893. effect.setVector2("depthValues", depthValues);
  73894. }
  73895. };
  73896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73897. // Smooth
  73898. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73899. // Merge
  73900. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73901. this.volumetricLightMergePostProces.onApply = function (effect) {
  73902. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73903. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73904. };
  73905. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73906. };
  73907. // Create luminance
  73908. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73909. var _this = this;
  73910. // Create luminance
  73911. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73912. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73913. var offsets = [];
  73914. this.luminancePostProcess.onApply = function (effect) {
  73915. var sU = (1.0 / _this.luminancePostProcess.width);
  73916. var sV = (1.0 / _this.luminancePostProcess.height);
  73917. offsets[0] = -0.5 * sU;
  73918. offsets[1] = 0.5 * sV;
  73919. offsets[2] = 0.5 * sU;
  73920. offsets[3] = 0.5 * sV;
  73921. offsets[4] = -0.5 * sU;
  73922. offsets[5] = -0.5 * sV;
  73923. offsets[6] = 0.5 * sU;
  73924. offsets[7] = -0.5 * sV;
  73925. effect.setArray2("lumOffsets", offsets);
  73926. };
  73927. // Add to pipeline
  73928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73929. // Create down sample luminance
  73930. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73931. var size = Math.pow(3, i);
  73932. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73933. if (i === 0) {
  73934. defines += "#define FINAL_DOWN_SAMPLER";
  73935. }
  73936. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73937. this.luminanceDownSamplePostProcesses.push(postProcess);
  73938. }
  73939. // Create callbacks and add effects
  73940. var lastLuminance = this.luminancePostProcess;
  73941. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73942. var downSampleOffsets = new Array(18);
  73943. pp.onApply = function (effect) {
  73944. if (!lastLuminance) {
  73945. return;
  73946. }
  73947. var id = 0;
  73948. for (var x = -1; x < 2; x++) {
  73949. for (var y = -1; y < 2; y++) {
  73950. downSampleOffsets[id] = x / lastLuminance.width;
  73951. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73952. id += 2;
  73953. }
  73954. }
  73955. effect.setArray2("dsOffsets", downSampleOffsets);
  73956. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73957. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73958. lastLuminance = _this.luminancePostProcess;
  73959. }
  73960. else {
  73961. lastLuminance = pp;
  73962. }
  73963. };
  73964. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73965. pp.onAfterRender = function (effect) {
  73966. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73967. 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);
  73968. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73969. };
  73970. }
  73971. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73972. });
  73973. };
  73974. // Create HDR post-process
  73975. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73976. var _this = this;
  73977. 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);
  73978. var outputLiminance = 1;
  73979. var time = 0;
  73980. var lastTime = 0;
  73981. this.hdrPostProcess.onApply = function (effect) {
  73982. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73983. time += scene.getEngine().getDeltaTime();
  73984. if (outputLiminance < 0) {
  73985. outputLiminance = _this._hdrCurrentLuminance;
  73986. }
  73987. else {
  73988. var dt = (lastTime - time) / 1000.0;
  73989. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73990. outputLiminance += _this.hdrDecreaseRate * dt;
  73991. }
  73992. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73993. outputLiminance -= _this.hdrIncreaseRate * dt;
  73994. }
  73995. else {
  73996. outputLiminance = _this._hdrCurrentLuminance;
  73997. }
  73998. }
  73999. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74000. effect.setFloat("averageLuminance", outputLiminance);
  74001. lastTime = time;
  74002. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74003. };
  74004. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74005. };
  74006. // Create lens flare post-process
  74007. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74008. var _this = this;
  74009. 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);
  74010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74011. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74012. 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);
  74013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74014. var resolution = new BABYLON.Vector2(0, 0);
  74015. // Lens flare
  74016. this.lensFlarePostProcess.onApply = function (effect) {
  74017. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74018. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74019. effect.setFloat("strength", _this.lensFlareStrength);
  74020. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74021. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74022. // Shift
  74023. resolution.x = _this.lensFlarePostProcess.width;
  74024. resolution.y = _this.lensFlarePostProcess.height;
  74025. effect.setVector2("resolution", resolution);
  74026. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74027. };
  74028. // Compose
  74029. 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);
  74030. 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);
  74031. this.lensFlareComposePostProcess.onApply = function (effect) {
  74032. if (!_this._scene.activeCamera) {
  74033. return;
  74034. }
  74035. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74036. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74037. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74038. // Lens start rotation matrix
  74039. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74040. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74041. 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));
  74042. camRot *= 4.0;
  74043. 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);
  74044. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74045. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74046. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74047. };
  74048. };
  74049. // Create depth-of-field post-process
  74050. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74051. var _this = this;
  74052. 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);
  74053. this.depthOfFieldPostProcess.onApply = function (effect) {
  74054. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74055. effect.setTexture("depthSampler", _this._getDepthTexture());
  74056. effect.setFloat("distance", _this.depthOfFieldDistance);
  74057. };
  74058. // Add to pipeline
  74059. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74060. };
  74061. // Create motion blur post-process
  74062. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74063. var _this = this;
  74064. 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);
  74065. var motionScale = 0;
  74066. var prevViewProjection = BABYLON.Matrix.Identity();
  74067. var invViewProjection = BABYLON.Matrix.Identity();
  74068. var viewProjection = BABYLON.Matrix.Identity();
  74069. var screenSize = BABYLON.Vector2.Zero();
  74070. this.motionBlurPostProcess.onApply = function (effect) {
  74071. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74072. viewProjection.invertToRef(invViewProjection);
  74073. effect.setMatrix("inverseViewProjection", invViewProjection);
  74074. effect.setMatrix("prevViewProjection", prevViewProjection);
  74075. prevViewProjection = viewProjection;
  74076. screenSize.x = _this.motionBlurPostProcess.width;
  74077. screenSize.y = _this.motionBlurPostProcess.height;
  74078. effect.setVector2("screenSize", screenSize);
  74079. motionScale = scene.getEngine().getFps() / 60.0;
  74080. effect.setFloat("motionScale", motionScale);
  74081. effect.setFloat("motionStrength", _this.motionStrength);
  74082. effect.setTexture("depthSampler", _this._getDepthTexture());
  74083. };
  74084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74085. };
  74086. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74087. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74088. var renderer = this._scene.enableGeometryBufferRenderer();
  74089. return renderer.getGBuffer().textures[0];
  74090. }
  74091. return this._scene.enableDepthRenderer().getDepthMap();
  74092. };
  74093. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74094. for (var i = 0; i < this._cameras.length; i++) {
  74095. var camera = this._cameras[i];
  74096. if (this.originalPostProcess) {
  74097. this.originalPostProcess.dispose(camera);
  74098. }
  74099. if (this.downSampleX4PostProcess) {
  74100. this.downSampleX4PostProcess.dispose(camera);
  74101. }
  74102. if (this.brightPassPostProcess) {
  74103. this.brightPassPostProcess.dispose(camera);
  74104. }
  74105. if (this.textureAdderPostProcess) {
  74106. this.textureAdderPostProcess.dispose(camera);
  74107. }
  74108. if (this.textureAdderFinalPostProcess) {
  74109. this.textureAdderFinalPostProcess.dispose(camera);
  74110. }
  74111. if (this.volumetricLightPostProcess) {
  74112. this.volumetricLightPostProcess.dispose(camera);
  74113. }
  74114. if (this.volumetricLightSmoothXPostProcess) {
  74115. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74116. }
  74117. if (this.volumetricLightSmoothYPostProcess) {
  74118. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74119. }
  74120. if (this.volumetricLightMergePostProces) {
  74121. this.volumetricLightMergePostProces.dispose(camera);
  74122. }
  74123. if (this.volumetricLightFinalPostProcess) {
  74124. this.volumetricLightFinalPostProcess.dispose(camera);
  74125. }
  74126. if (this.lensFlarePostProcess) {
  74127. this.lensFlarePostProcess.dispose(camera);
  74128. }
  74129. if (this.lensFlareComposePostProcess) {
  74130. this.lensFlareComposePostProcess.dispose(camera);
  74131. }
  74132. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74133. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74134. }
  74135. if (this.luminancePostProcess) {
  74136. this.luminancePostProcess.dispose(camera);
  74137. }
  74138. if (this.hdrPostProcess) {
  74139. this.hdrPostProcess.dispose(camera);
  74140. }
  74141. if (this.hdrFinalPostProcess) {
  74142. this.hdrFinalPostProcess.dispose(camera);
  74143. }
  74144. if (this.depthOfFieldPostProcess) {
  74145. this.depthOfFieldPostProcess.dispose(camera);
  74146. }
  74147. if (this.motionBlurPostProcess) {
  74148. this.motionBlurPostProcess.dispose(camera);
  74149. }
  74150. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74151. this.blurHPostProcesses[j].dispose(camera);
  74152. }
  74153. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74154. this.blurVPostProcesses[j].dispose(camera);
  74155. }
  74156. }
  74157. this.originalPostProcess = null;
  74158. this.downSampleX4PostProcess = null;
  74159. this.brightPassPostProcess = null;
  74160. this.textureAdderPostProcess = null;
  74161. this.textureAdderFinalPostProcess = null;
  74162. this.volumetricLightPostProcess = null;
  74163. this.volumetricLightSmoothXPostProcess = null;
  74164. this.volumetricLightSmoothYPostProcess = null;
  74165. this.volumetricLightMergePostProces = null;
  74166. this.volumetricLightFinalPostProcess = null;
  74167. this.lensFlarePostProcess = null;
  74168. this.lensFlareComposePostProcess = null;
  74169. this.luminancePostProcess = null;
  74170. this.hdrPostProcess = null;
  74171. this.hdrFinalPostProcess = null;
  74172. this.depthOfFieldPostProcess = null;
  74173. this.motionBlurPostProcess = null;
  74174. this.luminanceDownSamplePostProcesses = [];
  74175. this.blurHPostProcesses = [];
  74176. this.blurVPostProcesses = [];
  74177. };
  74178. // Dispose
  74179. StandardRenderingPipeline.prototype.dispose = function () {
  74180. this._disposePostProcesses();
  74181. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74182. _super.prototype.dispose.call(this);
  74183. };
  74184. // Serialize rendering pipeline
  74185. StandardRenderingPipeline.prototype.serialize = function () {
  74186. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74187. serializationObject.customType = "StandardRenderingPipeline";
  74188. return serializationObject;
  74189. };
  74190. /**
  74191. * Static members
  74192. */
  74193. // Parse serialized pipeline
  74194. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74195. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74196. };
  74197. // Luminance steps
  74198. StandardRenderingPipeline.LuminanceSteps = 6;
  74199. __decorate([
  74200. BABYLON.serialize()
  74201. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74202. __decorate([
  74203. BABYLON.serialize()
  74204. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74205. __decorate([
  74206. BABYLON.serialize()
  74207. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74208. __decorate([
  74209. BABYLON.serialize()
  74210. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74211. __decorate([
  74212. BABYLON.serializeAsTexture("lensTexture")
  74213. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74214. __decorate([
  74215. BABYLON.serialize()
  74216. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74217. __decorate([
  74218. BABYLON.serialize()
  74219. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74220. __decorate([
  74221. BABYLON.serialize()
  74222. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74223. __decorate([
  74224. BABYLON.serialize()
  74225. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74226. __decorate([
  74227. BABYLON.serialize()
  74228. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74229. __decorate([
  74230. BABYLON.serialize()
  74231. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74232. __decorate([
  74233. BABYLON.serializeAsTexture("lensColorTexture")
  74234. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74235. __decorate([
  74236. BABYLON.serialize()
  74237. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74238. __decorate([
  74239. BABYLON.serialize()
  74240. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74241. __decorate([
  74242. BABYLON.serialize()
  74243. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74244. __decorate([
  74245. BABYLON.serialize()
  74246. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74247. __decorate([
  74248. BABYLON.serializeAsTexture("lensStarTexture")
  74249. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74250. __decorate([
  74251. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74252. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74253. __decorate([
  74254. BABYLON.serialize()
  74255. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74256. __decorate([
  74257. BABYLON.serialize()
  74258. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74259. __decorate([
  74260. BABYLON.serialize()
  74261. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74262. __decorate([
  74263. BABYLON.serialize()
  74264. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74265. __decorate([
  74266. BABYLON.serialize()
  74267. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74268. __decorate([
  74269. BABYLON.serialize()
  74270. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74271. __decorate([
  74272. BABYLON.serialize()
  74273. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74274. __decorate([
  74275. BABYLON.serialize()
  74276. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74277. __decorate([
  74278. BABYLON.serialize()
  74279. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74280. __decorate([
  74281. BABYLON.serialize()
  74282. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74283. __decorate([
  74284. BABYLON.serialize()
  74285. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74286. __decorate([
  74287. BABYLON.serialize()
  74288. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74289. return StandardRenderingPipeline;
  74290. }(BABYLON.PostProcessRenderPipeline));
  74291. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74292. })(BABYLON || (BABYLON = {}));
  74293. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74294. var BABYLON;
  74295. (function (BABYLON) {
  74296. var FxaaPostProcess = /** @class */ (function (_super) {
  74297. __extends(FxaaPostProcess, _super);
  74298. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74299. if (camera === void 0) { camera = null; }
  74300. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74301. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74302. _this.onApplyObservable.add(function (effect) {
  74303. var texelSize = _this.texelSize;
  74304. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74305. });
  74306. return _this;
  74307. }
  74308. return FxaaPostProcess;
  74309. }(BABYLON.PostProcess));
  74310. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74311. })(BABYLON || (BABYLON = {}));
  74312. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74313. var BABYLON;
  74314. (function (BABYLON) {
  74315. /**
  74316. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74317. */
  74318. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74319. __extends(ChromaticAberrationPostProcess, _super);
  74320. /**
  74321. * Creates a new instance ChromaticAberrationPostProcess
  74322. * @param name The name of the effect.
  74323. * @param screenWidth The width of the screen to apply the effect on.
  74324. * @param screenHeight The height of the screen to apply the effect on.
  74325. * @param options The required width/height ratio to downsize to before computing the render pass.
  74326. * @param camera The camera to apply the render pass to.
  74327. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74328. * @param engine The engine which the post process will be applied. (default: current engine)
  74329. * @param reusable If the post process can be reused on the same frame. (default: false)
  74330. * @param textureType Type of textures used when performing the post process. (default: 0)
  74331. * @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)
  74332. */
  74333. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74334. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74335. if (blockCompilation === void 0) { blockCompilation = false; }
  74336. 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;
  74337. /**
  74338. * The amount of seperation of rgb channels (default: 30)
  74339. */
  74340. _this.aberrationAmount = 30;
  74341. /**
  74342. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74343. */
  74344. _this.radialIntensity = 0;
  74345. /**
  74346. * 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))
  74347. */
  74348. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74349. /**
  74350. * 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))
  74351. */
  74352. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74353. _this.onApplyObservable.add(function (effect) {
  74354. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74355. effect.setFloat('screen_width', screenWidth);
  74356. effect.setFloat('screen_height', screenHeight);
  74357. effect.setFloat('radialIntensity', _this.radialIntensity);
  74358. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74359. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74360. });
  74361. return _this;
  74362. }
  74363. return ChromaticAberrationPostProcess;
  74364. }(BABYLON.PostProcess));
  74365. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74366. })(BABYLON || (BABYLON = {}));
  74367. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74368. var BABYLON;
  74369. (function (BABYLON) {
  74370. /**
  74371. * The GrainPostProcess adds noise to the image at mid luminance levels
  74372. */
  74373. var GrainPostProcess = /** @class */ (function (_super) {
  74374. __extends(GrainPostProcess, _super);
  74375. /**
  74376. * Creates a new instance of @see GrainPostProcess
  74377. * @param name The name of the effect.
  74378. * @param options The required width/height ratio to downsize to before computing the render pass.
  74379. * @param camera The camera to apply the render pass to.
  74380. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74381. * @param engine The engine which the post process will be applied. (default: current engine)
  74382. * @param reusable If the post process can be reused on the same frame. (default: false)
  74383. * @param textureType Type of textures used when performing the post process. (default: 0)
  74384. * @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)
  74385. */
  74386. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74387. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74388. if (blockCompilation === void 0) { blockCompilation = false; }
  74389. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74390. /**
  74391. * The intensity of the grain added (default: 30)
  74392. */
  74393. _this.intensity = 30;
  74394. /**
  74395. * If the grain should be randomized on every frame
  74396. */
  74397. _this.animated = false;
  74398. _this.onApplyObservable.add(function (effect) {
  74399. effect.setFloat('intensity', _this.intensity);
  74400. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74401. });
  74402. return _this;
  74403. }
  74404. return GrainPostProcess;
  74405. }(BABYLON.PostProcess));
  74406. BABYLON.GrainPostProcess = GrainPostProcess;
  74407. })(BABYLON || (BABYLON = {}));
  74408. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74409. var BABYLON;
  74410. (function (BABYLON) {
  74411. /**
  74412. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74413. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74414. */
  74415. var SharpenPostProcess = /** @class */ (function (_super) {
  74416. __extends(SharpenPostProcess, _super);
  74417. /**
  74418. * Creates a new instance ConvolutionPostProcess
  74419. * @param name The name of the effect.
  74420. * @param options The required width/height ratio to downsize to before computing the render pass.
  74421. * @param camera The camera to apply the render pass to.
  74422. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74423. * @param engine The engine which the post process will be applied. (default: current engine)
  74424. * @param reusable If the post process can be reused on the same frame. (default: false)
  74425. * @param textureType Type of textures used when performing the post process. (default: 0)
  74426. * @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)
  74427. */
  74428. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74429. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74430. if (blockCompilation === void 0) { blockCompilation = false; }
  74431. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74432. /**
  74433. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74434. */
  74435. _this.colorAmount = 1.0;
  74436. /**
  74437. * How much sharpness should be applied (default: 0.3)
  74438. */
  74439. _this.edgeAmount = 0.3;
  74440. _this.onApply = function (effect) {
  74441. effect.setFloat2("screenSize", _this.width, _this.height);
  74442. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74443. };
  74444. return _this;
  74445. }
  74446. return SharpenPostProcess;
  74447. }(BABYLON.PostProcess));
  74448. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74449. })(BABYLON || (BABYLON = {}));
  74450. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74451. var BABYLON;
  74452. (function (BABYLON) {
  74453. /**
  74454. * The Blur Post Process which blurs an image based on a kernel and direction.
  74455. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74456. */
  74457. var BlurPostProcess = /** @class */ (function (_super) {
  74458. __extends(BlurPostProcess, _super);
  74459. /**
  74460. * Creates a new instance BlurPostProcess
  74461. * @param name The name of the effect.
  74462. * @param direction The direction in which to blur the image.
  74463. * @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.
  74464. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74465. * @param camera The camera to apply the render pass to.
  74466. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74467. * @param engine The engine which the post process will be applied. (default: current engine)
  74468. * @param reusable If the post process can be reused on the same frame. (default: false)
  74469. * @param textureType Type of textures used when performing the post process. (default: 0)
  74470. * @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)
  74471. */
  74472. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74474. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74475. if (defines === void 0) { defines = ""; }
  74476. if (blockCompilation === void 0) { blockCompilation = false; }
  74477. 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;
  74478. _this.direction = direction;
  74479. _this.blockCompilation = blockCompilation;
  74480. _this._packedFloat = false;
  74481. _this._staticDefines = "";
  74482. _this._staticDefines = defines;
  74483. _this.onApplyObservable.add(function (effect) {
  74484. if (_this._outputTexture) {
  74485. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74486. }
  74487. else {
  74488. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74489. }
  74490. });
  74491. _this.kernel = kernel;
  74492. return _this;
  74493. }
  74494. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74495. /**
  74496. * Gets the length in pixels of the blur sample region
  74497. */
  74498. get: function () {
  74499. return this._idealKernel;
  74500. },
  74501. /**
  74502. * Sets the length in pixels of the blur sample region
  74503. */
  74504. set: function (v) {
  74505. if (this._idealKernel === v) {
  74506. return;
  74507. }
  74508. v = Math.max(v, 1);
  74509. this._idealKernel = v;
  74510. this._kernel = this._nearestBestKernel(v);
  74511. if (!this.blockCompilation) {
  74512. this._updateParameters();
  74513. }
  74514. },
  74515. enumerable: true,
  74516. configurable: true
  74517. });
  74518. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74519. /**
  74520. * Gets wether or not the blur is unpacking/repacking floats
  74521. */
  74522. get: function () {
  74523. return this._packedFloat;
  74524. },
  74525. /**
  74526. * Sets wether or not the blur needs to unpack/repack floats
  74527. */
  74528. set: function (v) {
  74529. if (this._packedFloat === v) {
  74530. return;
  74531. }
  74532. this._packedFloat = v;
  74533. if (!this.blockCompilation) {
  74534. this._updateParameters();
  74535. }
  74536. },
  74537. enumerable: true,
  74538. configurable: true
  74539. });
  74540. /**
  74541. * Updates the effect with the current post process compile time values and recompiles the shader.
  74542. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74543. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74544. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74545. * @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
  74546. * @param onCompiled Called when the shader has been compiled.
  74547. * @param onError Called if there is an error when compiling a shader.
  74548. */
  74549. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74550. if (defines === void 0) { defines = null; }
  74551. if (uniforms === void 0) { uniforms = null; }
  74552. if (samplers === void 0) { samplers = null; }
  74553. this._updateParameters(onCompiled, onError);
  74554. };
  74555. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74556. // Generate sampling offsets and weights
  74557. var N = this._kernel;
  74558. var centerIndex = (N - 1) / 2;
  74559. // Generate Gaussian sampling weights over kernel
  74560. var offsets = [];
  74561. var weights = [];
  74562. var totalWeight = 0;
  74563. for (var i = 0; i < N; i++) {
  74564. var u = i / (N - 1);
  74565. var w = this._gaussianWeight(u * 2.0 - 1);
  74566. offsets[i] = (i - centerIndex);
  74567. weights[i] = w;
  74568. totalWeight += w;
  74569. }
  74570. // Normalize weights
  74571. for (var i = 0; i < weights.length; i++) {
  74572. weights[i] /= totalWeight;
  74573. }
  74574. // Optimize: combine samples to take advantage of hardware linear sampling
  74575. // Walk from left to center, combining pairs (symmetrically)
  74576. var linearSamplingWeights = [];
  74577. var linearSamplingOffsets = [];
  74578. var linearSamplingMap = [];
  74579. for (var i = 0; i <= centerIndex; i += 2) {
  74580. var j = Math.min(i + 1, Math.floor(centerIndex));
  74581. var singleCenterSample = i === j;
  74582. if (singleCenterSample) {
  74583. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74584. }
  74585. else {
  74586. var sharedCell = j === centerIndex;
  74587. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74588. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74589. if (offsetLinear === 0) {
  74590. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74591. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74592. }
  74593. else {
  74594. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74595. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74596. }
  74597. }
  74598. }
  74599. for (var i = 0; i < linearSamplingMap.length; i++) {
  74600. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74601. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74602. }
  74603. // Replace with optimized
  74604. offsets = linearSamplingOffsets;
  74605. weights = linearSamplingWeights;
  74606. // Generate shaders
  74607. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74608. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74609. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74610. var defines = "";
  74611. defines += this._staticDefines;
  74612. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74613. if (this._staticDefines.indexOf("DOF") != -1) {
  74614. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74615. varyingCount--;
  74616. }
  74617. for (var i = 0; i < varyingCount; i++) {
  74618. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74619. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74620. }
  74621. var depCount = 0;
  74622. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74623. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74624. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74625. depCount++;
  74626. }
  74627. if (this.packedFloat) {
  74628. defines += "#define PACKEDFLOAT 1";
  74629. }
  74630. this.blockCompilation = false;
  74631. _super.prototype.updateEffect.call(this, defines, null, null, {
  74632. varyingCount: varyingCount,
  74633. depCount: depCount
  74634. }, onCompiled, onError);
  74635. };
  74636. /**
  74637. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74638. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74639. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74640. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74641. * The gaps between physical kernels are compensated for in the weighting of the samples
  74642. * @param idealKernel Ideal blur kernel.
  74643. * @return Nearest best kernel.
  74644. */
  74645. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74646. var v = Math.round(idealKernel);
  74647. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74648. var k = _a[_i];
  74649. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74650. return Math.max(k, 3);
  74651. }
  74652. }
  74653. return Math.max(v, 3);
  74654. };
  74655. /**
  74656. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74657. * @param x The point on the Gaussian distribution to sample.
  74658. * @return the value of the Gaussian function at x.
  74659. */
  74660. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74661. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74662. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74663. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74664. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74665. // truncated at around 1.3% of peak strength.
  74666. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74667. var sigma = (1 / 3);
  74668. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74669. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74670. var weight = (1.0 / denominator) * Math.exp(exponent);
  74671. return weight;
  74672. };
  74673. /**
  74674. * Generates a string that can be used as a floating point number in GLSL.
  74675. * @param x Value to print.
  74676. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74677. * @return GLSL float string.
  74678. */
  74679. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74680. if (decimalFigures === void 0) { decimalFigures = 8; }
  74681. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74682. };
  74683. return BlurPostProcess;
  74684. }(BABYLON.PostProcess));
  74685. BABYLON.BlurPostProcess = BlurPostProcess;
  74686. })(BABYLON || (BABYLON = {}));
  74687. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74688. var BABYLON;
  74689. (function (BABYLON) {
  74690. /**
  74691. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74692. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74693. * based on samples that have a large difference in distance than the center pixel.
  74694. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74695. */
  74696. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74697. __extends(DepthOfFieldBlurPostProcess, _super);
  74698. /**
  74699. * Creates a new instance CircleOfConfusionPostProcess
  74700. * @param name The name of the effect.
  74701. * @param scene The scene the effect belongs to.
  74702. * @param direction The direction the blur should be applied.
  74703. * @param kernel The size of the kernel used to blur.
  74704. * @param options The required width/height ratio to downsize to before computing the render pass.
  74705. * @param camera The camera to apply the render pass to.
  74706. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74707. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74708. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74709. * @param engine The engine which the post process will be applied. (default: current engine)
  74710. * @param reusable If the post process can be reused on the same frame. (default: false)
  74711. * @param textureType Type of textures used when performing the post process. (default: 0)
  74712. * @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)
  74713. */
  74714. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74715. if (imageToBlur === void 0) { imageToBlur = null; }
  74716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74717. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74718. if (blockCompilation === void 0) { blockCompilation = false; }
  74719. 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;
  74720. _this.direction = direction;
  74721. _this.onApplyObservable.add(function (effect) {
  74722. if (imageToBlur != null) {
  74723. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74724. }
  74725. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74726. if (scene.activeCamera) {
  74727. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74728. }
  74729. });
  74730. return _this;
  74731. }
  74732. return DepthOfFieldBlurPostProcess;
  74733. }(BABYLON.BlurPostProcess));
  74734. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74735. })(BABYLON || (BABYLON = {}));
  74736. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74737. var BABYLON;
  74738. (function (BABYLON) {
  74739. /**
  74740. * Options to be set when merging outputs from the default pipeline.
  74741. */
  74742. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74743. function DepthOfFieldMergePostProcessOptions() {
  74744. }
  74745. return DepthOfFieldMergePostProcessOptions;
  74746. }());
  74747. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74748. /**
  74749. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74750. */
  74751. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74752. __extends(DepthOfFieldMergePostProcess, _super);
  74753. /**
  74754. * Creates a new instance of DepthOfFieldMergePostProcess
  74755. * @param name The name of the effect.
  74756. * @param originalFromInput Post process which's input will be used for the merge.
  74757. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74758. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74759. * @param options The required width/height ratio to downsize to before computing the render pass.
  74760. * @param camera The camera to apply the render pass to.
  74761. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74762. * @param engine The engine which the post process will be applied. (default: current engine)
  74763. * @param reusable If the post process can be reused on the same frame. (default: false)
  74764. * @param textureType Type of textures used when performing the post process. (default: 0)
  74765. * @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)
  74766. */
  74767. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74769. if (blockCompilation === void 0) { blockCompilation = false; }
  74770. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74771. _this.blurSteps = blurSteps;
  74772. _this.onApplyObservable.add(function (effect) {
  74773. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74774. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74775. blurSteps.forEach(function (step, index) {
  74776. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74777. });
  74778. });
  74779. if (!blockCompilation) {
  74780. _this.updateEffect();
  74781. }
  74782. return _this;
  74783. }
  74784. /**
  74785. * Updates the effect with the current post process compile time values and recompiles the shader.
  74786. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74787. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74788. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74789. * @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
  74790. * @param onCompiled Called when the shader has been compiled.
  74791. * @param onError Called if there is an error when compiling a shader.
  74792. */
  74793. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74794. if (defines === void 0) { defines = null; }
  74795. if (uniforms === void 0) { uniforms = null; }
  74796. if (samplers === void 0) { samplers = null; }
  74797. if (!defines) {
  74798. defines = "";
  74799. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74800. }
  74801. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74802. };
  74803. return DepthOfFieldMergePostProcess;
  74804. }(BABYLON.PostProcess));
  74805. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74806. })(BABYLON || (BABYLON = {}));
  74807. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74808. var BABYLON;
  74809. (function (BABYLON) {
  74810. /**
  74811. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74812. */
  74813. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74814. __extends(CircleOfConfusionPostProcess, _super);
  74815. /**
  74816. * Creates a new instance CircleOfConfusionPostProcess
  74817. * @param name The name of the effect.
  74818. * @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.
  74819. * @param options The required width/height ratio to downsize to before computing the render pass.
  74820. * @param camera The camera to apply the render pass to.
  74821. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74822. * @param engine The engine which the post process will be applied. (default: current engine)
  74823. * @param reusable If the post process can be reused on the same frame. (default: false)
  74824. * @param textureType Type of textures used when performing the post process. (default: 0)
  74825. * @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)
  74826. */
  74827. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74828. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74829. if (blockCompilation === void 0) { blockCompilation = false; }
  74830. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74831. /**
  74832. * 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.
  74833. */
  74834. _this.lensSize = 50;
  74835. /**
  74836. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74837. */
  74838. _this.fStop = 1.4;
  74839. /**
  74840. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74841. */
  74842. _this.focusDistance = 2000;
  74843. /**
  74844. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74845. */
  74846. _this.focalLength = 50;
  74847. _this._depthTexture = null;
  74848. _this._depthTexture = depthTexture;
  74849. _this.onApplyObservable.add(function (effect) {
  74850. if (!_this._depthTexture) {
  74851. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74852. return;
  74853. }
  74854. effect.setTexture("depthSampler", _this._depthTexture);
  74855. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74856. var aperture = _this.lensSize / _this.fStop;
  74857. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74858. effect.setFloat('focusDistance', _this.focusDistance);
  74859. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74860. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74861. });
  74862. return _this;
  74863. }
  74864. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74865. /**
  74866. * 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.
  74867. */
  74868. set: function (value) {
  74869. this._depthTexture = value;
  74870. },
  74871. enumerable: true,
  74872. configurable: true
  74873. });
  74874. return CircleOfConfusionPostProcess;
  74875. }(BABYLON.PostProcess));
  74876. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74877. })(BABYLON || (BABYLON = {}));
  74878. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74879. var BABYLON;
  74880. (function (BABYLON) {
  74881. /**
  74882. * Specifies the level of max blur that should be applied when using the depth of field effect
  74883. */
  74884. var DepthOfFieldEffectBlurLevel;
  74885. (function (DepthOfFieldEffectBlurLevel) {
  74886. /**
  74887. * Subtle blur
  74888. */
  74889. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74890. /**
  74891. * Medium blur
  74892. */
  74893. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74894. /**
  74895. * Large blur
  74896. */
  74897. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74898. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74899. ;
  74900. /**
  74901. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74902. */
  74903. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74904. __extends(DepthOfFieldEffect, _super);
  74905. /**
  74906. * Creates a new instance DepthOfFieldEffect
  74907. * @param scene The scene the effect belongs to.
  74908. * @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.
  74909. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74910. * @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)
  74911. */
  74912. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74913. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74914. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74915. if (blockCompilation === void 0) { blockCompilation = false; }
  74916. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74917. return _this._effects;
  74918. }, true) || this;
  74919. /**
  74920. * Internal post processes in depth of field effect
  74921. */
  74922. _this._effects = [];
  74923. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74924. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74925. // 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)
  74926. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74927. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74928. _this._depthOfFieldBlurY = [];
  74929. _this._depthOfFieldBlurX = [];
  74930. var blurCount = 1;
  74931. var kernelSize = 15;
  74932. switch (blurLevel) {
  74933. case DepthOfFieldEffectBlurLevel.High: {
  74934. blurCount = 3;
  74935. kernelSize = 51;
  74936. break;
  74937. }
  74938. case DepthOfFieldEffectBlurLevel.Medium: {
  74939. blurCount = 2;
  74940. kernelSize = 31;
  74941. break;
  74942. }
  74943. default: {
  74944. kernelSize = 15;
  74945. blurCount = 1;
  74946. break;
  74947. }
  74948. }
  74949. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74950. var ratio = 1.0;
  74951. for (var i = 0; i < blurCount; i++) {
  74952. 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);
  74953. blurY.autoClear = false;
  74954. ratio = 0.75 / Math.pow(2, i);
  74955. 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);
  74956. blurX.autoClear = false;
  74957. _this._depthOfFieldBlurY.push(blurY);
  74958. _this._depthOfFieldBlurX.push(blurX);
  74959. }
  74960. // Set all post processes on the effect.
  74961. _this._effects = [_this._circleOfConfusion];
  74962. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74963. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74964. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74965. }
  74966. // Merge blurred images with original image based on circleOfConfusion
  74967. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74968. _this._dofMerge.autoClear = false;
  74969. _this._effects.push(_this._dofMerge);
  74970. return _this;
  74971. }
  74972. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74973. get: function () {
  74974. return this._circleOfConfusion.focalLength;
  74975. },
  74976. /**
  74977. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74978. */
  74979. set: function (value) {
  74980. this._circleOfConfusion.focalLength = value;
  74981. },
  74982. enumerable: true,
  74983. configurable: true
  74984. });
  74985. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74986. get: function () {
  74987. return this._circleOfConfusion.fStop;
  74988. },
  74989. /**
  74990. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74991. */
  74992. set: function (value) {
  74993. this._circleOfConfusion.fStop = value;
  74994. },
  74995. enumerable: true,
  74996. configurable: true
  74997. });
  74998. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74999. get: function () {
  75000. return this._circleOfConfusion.focusDistance;
  75001. },
  75002. /**
  75003. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75004. */
  75005. set: function (value) {
  75006. this._circleOfConfusion.focusDistance = value;
  75007. },
  75008. enumerable: true,
  75009. configurable: true
  75010. });
  75011. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75012. get: function () {
  75013. return this._circleOfConfusion.lensSize;
  75014. },
  75015. /**
  75016. * 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.
  75017. */
  75018. set: function (value) {
  75019. this._circleOfConfusion.lensSize = value;
  75020. },
  75021. enumerable: true,
  75022. configurable: true
  75023. });
  75024. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75025. /**
  75026. * 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.
  75027. */
  75028. set: function (value) {
  75029. this._circleOfConfusion.depthTexture = value;
  75030. },
  75031. enumerable: true,
  75032. configurable: true
  75033. });
  75034. /**
  75035. * Disposes each of the internal effects for a given camera.
  75036. * @param camera The camera to dispose the effect on.
  75037. */
  75038. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75039. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75040. this._effects[effectIndex].dispose(camera);
  75041. }
  75042. };
  75043. /**
  75044. * Internal
  75045. */
  75046. DepthOfFieldEffect.prototype._updateEffects = function () {
  75047. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75048. this._effects[effectIndex].updateEffect();
  75049. }
  75050. };
  75051. /**
  75052. * Internal
  75053. * @returns if all the contained post processes are ready.
  75054. */
  75055. DepthOfFieldEffect.prototype._isReady = function () {
  75056. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75057. if (!this._effects[effectIndex].isReady()) {
  75058. return false;
  75059. }
  75060. }
  75061. return true;
  75062. };
  75063. return DepthOfFieldEffect;
  75064. }(BABYLON.PostProcessRenderEffect));
  75065. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75066. })(BABYLON || (BABYLON = {}));
  75067. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75068. var BABYLON;
  75069. (function (BABYLON) {
  75070. /**
  75071. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75072. */
  75073. var BloomMergePostProcess = /** @class */ (function (_super) {
  75074. __extends(BloomMergePostProcess, _super);
  75075. /**
  75076. * Creates a new instance of @see BloomMergePostProcess
  75077. * @param name The name of the effect.
  75078. * @param originalFromInput Post process which's input will be used for the merge.
  75079. * @param blurred Blurred highlights post process which's output will be used.
  75080. * @param weight Weight of the bloom to be added to the original input.
  75081. * @param options The required width/height ratio to downsize to before computing the render pass.
  75082. * @param camera The camera to apply the render pass to.
  75083. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75084. * @param engine The engine which the post process will be applied. (default: current engine)
  75085. * @param reusable If the post process can be reused on the same frame. (default: false)
  75086. * @param textureType Type of textures used when performing the post process. (default: 0)
  75087. * @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)
  75088. */
  75089. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75090. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75091. if (blockCompilation === void 0) { blockCompilation = false; }
  75092. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75093. _this.weight = weight;
  75094. _this.onApplyObservable.add(function (effect) {
  75095. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75096. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75097. effect.setFloat("bloomWeight", _this.weight);
  75098. });
  75099. if (!blockCompilation) {
  75100. _this.updateEffect();
  75101. }
  75102. return _this;
  75103. }
  75104. return BloomMergePostProcess;
  75105. }(BABYLON.PostProcess));
  75106. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75107. })(BABYLON || (BABYLON = {}));
  75108. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75109. var BABYLON;
  75110. (function (BABYLON) {
  75111. /**
  75112. * 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.
  75113. */
  75114. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75115. __extends(ExtractHighlightsPostProcess, _super);
  75116. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75117. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75118. if (blockCompilation === void 0) { blockCompilation = false; }
  75119. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75120. /**
  75121. * The luminance threshold, pixels below this value will be set to black.
  75122. */
  75123. _this.threshold = 0.9;
  75124. /**
  75125. * Internal
  75126. */
  75127. _this._exposure = 1;
  75128. /**
  75129. * Post process which has the input texture to be used when performing highlight extraction
  75130. */
  75131. _this._inputPostProcess = null;
  75132. _this.onApplyObservable.add(function (effect) {
  75133. if (_this._inputPostProcess) {
  75134. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75135. }
  75136. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75137. effect.setFloat('exposure', _this._exposure);
  75138. });
  75139. return _this;
  75140. }
  75141. return ExtractHighlightsPostProcess;
  75142. }(BABYLON.PostProcess));
  75143. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75144. })(BABYLON || (BABYLON = {}));
  75145. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75146. var BABYLON;
  75147. (function (BABYLON) {
  75148. /**
  75149. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75150. */
  75151. var BloomEffect = /** @class */ (function (_super) {
  75152. __extends(BloomEffect, _super);
  75153. /**
  75154. * Creates a new instance of @see BloomEffect
  75155. * @param scene The scene the effect belongs to.
  75156. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75157. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75158. * @param bloomWeight The the strength of bloom.
  75159. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75160. * @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)
  75161. */
  75162. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75163. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75164. if (blockCompilation === void 0) { blockCompilation = false; }
  75165. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75166. return _this._effects;
  75167. }, true) || this;
  75168. _this.bloomScale = bloomScale;
  75169. /**
  75170. * Internal
  75171. */
  75172. _this._effects = [];
  75173. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75174. _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);
  75175. _this._blurX.alwaysForcePOT = true;
  75176. _this._blurX.autoClear = false;
  75177. _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);
  75178. _this._blurY.alwaysForcePOT = true;
  75179. _this._blurY.autoClear = false;
  75180. _this.kernel = bloomKernel;
  75181. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75182. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75183. _this._merge.autoClear = false;
  75184. _this._effects.push(_this._merge);
  75185. return _this;
  75186. }
  75187. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75188. /**
  75189. * The luminance threshold to find bright areas of the image to bloom.
  75190. */
  75191. get: function () {
  75192. return this._downscale.threshold;
  75193. },
  75194. set: function (value) {
  75195. this._downscale.threshold = value;
  75196. },
  75197. enumerable: true,
  75198. configurable: true
  75199. });
  75200. Object.defineProperty(BloomEffect.prototype, "weight", {
  75201. /**
  75202. * The strength of the bloom.
  75203. */
  75204. get: function () {
  75205. return this._merge.weight;
  75206. },
  75207. set: function (value) {
  75208. this._merge.weight = value;
  75209. },
  75210. enumerable: true,
  75211. configurable: true
  75212. });
  75213. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75214. /**
  75215. * Specifies the size of the bloom blur kernel, relative to the final output size
  75216. */
  75217. get: function () {
  75218. return this._blurX.kernel / this.bloomScale;
  75219. },
  75220. set: function (value) {
  75221. this._blurX.kernel = value * this.bloomScale;
  75222. this._blurY.kernel = value * this.bloomScale;
  75223. },
  75224. enumerable: true,
  75225. configurable: true
  75226. });
  75227. /**
  75228. * Disposes each of the internal effects for a given camera.
  75229. * @param camera The camera to dispose the effect on.
  75230. */
  75231. BloomEffect.prototype.disposeEffects = function (camera) {
  75232. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75233. this._effects[effectIndex].dispose(camera);
  75234. }
  75235. };
  75236. /**
  75237. * Internal
  75238. */
  75239. BloomEffect.prototype._updateEffects = function () {
  75240. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75241. this._effects[effectIndex].updateEffect();
  75242. }
  75243. };
  75244. /**
  75245. * Internal
  75246. * @returns if all the contained post processes are ready.
  75247. */
  75248. BloomEffect.prototype._isReady = function () {
  75249. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75250. if (!this._effects[effectIndex].isReady()) {
  75251. return false;
  75252. }
  75253. }
  75254. return true;
  75255. };
  75256. return BloomEffect;
  75257. }(BABYLON.PostProcessRenderEffect));
  75258. BABYLON.BloomEffect = BloomEffect;
  75259. })(BABYLON || (BABYLON = {}));
  75260. //# sourceMappingURL=babylon.bloomEffect.js.map
  75261. var BABYLON;
  75262. (function (BABYLON) {
  75263. /**
  75264. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75265. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75266. */
  75267. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75268. __extends(DefaultRenderingPipeline, _super);
  75269. /**
  75270. * @constructor
  75271. * @param {string} name - The rendering pipeline name
  75272. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75273. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  75274. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75275. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75276. */
  75277. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75278. if (automaticBuild === void 0) { automaticBuild = true; }
  75279. var _this = _super.call(this, scene.getEngine(), name) || this;
  75280. _this._originalCameras = [];
  75281. /**
  75282. * ID of the sharpen post process,
  75283. */
  75284. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75285. /**
  75286. * ID of the image processing post process;
  75287. */
  75288. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75289. /**
  75290. * ID of the Fast Approximate Anti-Aliasing post process;
  75291. */
  75292. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75293. /**
  75294. * ID of the chromatic aberration post process,
  75295. */
  75296. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75297. /**
  75298. * ID of the grain post process
  75299. */
  75300. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75301. /**
  75302. * Animations which can be used to tweak settings over a period of time
  75303. */
  75304. _this.animations = [];
  75305. _this._imageProcessingConfigurationObserver = null;
  75306. // Values
  75307. _this._sharpenEnabled = false;
  75308. _this._bloomEnabled = false;
  75309. _this._depthOfFieldEnabled = false;
  75310. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75311. _this._fxaaEnabled = false;
  75312. _this._imageProcessingEnabled = true;
  75313. _this._bloomScale = 0.5;
  75314. _this._chromaticAberrationEnabled = false;
  75315. _this._grainEnabled = false;
  75316. _this._buildAllowed = true;
  75317. _this._resizeObserver = null;
  75318. _this._hardwareScaleLevel = 1.0;
  75319. _this._bloomKernel = 64;
  75320. /**
  75321. * Specifies the weight of the bloom in the final rendering
  75322. */
  75323. _this._bloomWeight = 0.15;
  75324. /**
  75325. * Specifies the luma threshold for the area that will be blurred by the bloom
  75326. */
  75327. _this._bloomThreshold = 0.9;
  75328. _this._samples = 1;
  75329. _this._hasCleared = false;
  75330. _this._prevPostProcess = null;
  75331. _this._prevPrevPostProcess = null;
  75332. _this._cameras = cameras || [];
  75333. _this._originalCameras = _this._cameras.slice();
  75334. _this._buildAllowed = automaticBuild;
  75335. // Initialize
  75336. _this._scene = scene;
  75337. var caps = _this._scene.getEngine().getCaps();
  75338. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75339. // Misc
  75340. if (_this._hdr) {
  75341. if (caps.textureHalfFloatRender) {
  75342. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75343. }
  75344. else if (caps.textureFloatRender) {
  75345. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75346. }
  75347. }
  75348. else {
  75349. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75350. }
  75351. // Attach
  75352. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75353. var engine = _this._scene.getEngine();
  75354. // Create post processes before hand so they can be modified before enabled.
  75355. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75356. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75357. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75358. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75359. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75360. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75361. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75362. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75363. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75364. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75365. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75366. _this.bloomKernel = _this.bloomKernel;
  75367. });
  75368. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75369. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75370. });
  75371. _this._buildPipeline();
  75372. return _this;
  75373. }
  75374. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75375. get: function () {
  75376. return this._sharpenEnabled;
  75377. },
  75378. /**
  75379. * Enable or disable the sharpen process from the pipeline
  75380. */
  75381. set: function (enabled) {
  75382. if (this._sharpenEnabled === enabled) {
  75383. return;
  75384. }
  75385. this._sharpenEnabled = enabled;
  75386. this._buildPipeline();
  75387. },
  75388. enumerable: true,
  75389. configurable: true
  75390. });
  75391. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75392. /**
  75393. * Specifies the size of the bloom blur kernel, relative to the final output size
  75394. */
  75395. get: function () {
  75396. return this._bloomKernel;
  75397. },
  75398. set: function (value) {
  75399. this._bloomKernel = value;
  75400. this.bloom.kernel = value / this._hardwareScaleLevel;
  75401. },
  75402. enumerable: true,
  75403. configurable: true
  75404. });
  75405. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75406. get: function () {
  75407. return this._bloomWeight;
  75408. },
  75409. /**
  75410. * The strength of the bloom.
  75411. */
  75412. set: function (value) {
  75413. if (this._bloomWeight === value) {
  75414. return;
  75415. }
  75416. this.bloom.weight = value;
  75417. this._bloomWeight = value;
  75418. },
  75419. enumerable: true,
  75420. configurable: true
  75421. });
  75422. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75423. get: function () {
  75424. return this._bloomThreshold;
  75425. },
  75426. /**
  75427. * The strength of the bloom.
  75428. */
  75429. set: function (value) {
  75430. if (this._bloomThreshold === value) {
  75431. return;
  75432. }
  75433. this.bloom.threshold = value;
  75434. this._bloomThreshold = value;
  75435. },
  75436. enumerable: true,
  75437. configurable: true
  75438. });
  75439. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75440. get: function () {
  75441. return this._bloomScale;
  75442. },
  75443. /**
  75444. * The scale of the bloom, lower value will provide better performance.
  75445. */
  75446. set: function (value) {
  75447. if (this._bloomScale === value) {
  75448. return;
  75449. }
  75450. this._bloomScale = value;
  75451. // recreate bloom and dispose old as this setting is not dynamic
  75452. this._rebuildBloom();
  75453. this._buildPipeline();
  75454. },
  75455. enumerable: true,
  75456. configurable: true
  75457. });
  75458. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75459. get: function () {
  75460. return this._bloomEnabled;
  75461. },
  75462. /**
  75463. * Enable or disable the bloom from the pipeline
  75464. */
  75465. set: function (enabled) {
  75466. if (this._bloomEnabled === enabled) {
  75467. return;
  75468. }
  75469. this._bloomEnabled = enabled;
  75470. this._buildPipeline();
  75471. },
  75472. enumerable: true,
  75473. configurable: true
  75474. });
  75475. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75476. // recreate bloom and dispose old as this setting is not dynamic
  75477. var oldBloom = this.bloom;
  75478. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75479. this.bloom.threshold = oldBloom.threshold;
  75480. for (var i = 0; i < this._cameras.length; i++) {
  75481. oldBloom.disposeEffects(this._cameras[i]);
  75482. }
  75483. };
  75484. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75485. /**
  75486. * If the depth of field is enabled.
  75487. */
  75488. get: function () {
  75489. return this._depthOfFieldEnabled;
  75490. },
  75491. set: function (enabled) {
  75492. if (this._depthOfFieldEnabled === enabled) {
  75493. return;
  75494. }
  75495. this._depthOfFieldEnabled = enabled;
  75496. this._buildPipeline();
  75497. },
  75498. enumerable: true,
  75499. configurable: true
  75500. });
  75501. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75502. /**
  75503. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75504. */
  75505. get: function () {
  75506. return this._depthOfFieldBlurLevel;
  75507. },
  75508. set: function (value) {
  75509. if (this._depthOfFieldBlurLevel === value) {
  75510. return;
  75511. }
  75512. this._depthOfFieldBlurLevel = value;
  75513. // recreate dof and dispose old as this setting is not dynamic
  75514. var oldDof = this.depthOfField;
  75515. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75516. this.depthOfField.focalLength = oldDof.focalLength;
  75517. this.depthOfField.focusDistance = oldDof.focusDistance;
  75518. this.depthOfField.fStop = oldDof.fStop;
  75519. this.depthOfField.lensSize = oldDof.lensSize;
  75520. for (var i = 0; i < this._cameras.length; i++) {
  75521. oldDof.disposeEffects(this._cameras[i]);
  75522. }
  75523. this._buildPipeline();
  75524. },
  75525. enumerable: true,
  75526. configurable: true
  75527. });
  75528. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75529. get: function () {
  75530. return this._fxaaEnabled;
  75531. },
  75532. /**
  75533. * If the anti aliasing is enabled.
  75534. */
  75535. set: function (enabled) {
  75536. if (this._fxaaEnabled === enabled) {
  75537. return;
  75538. }
  75539. this._fxaaEnabled = enabled;
  75540. this._buildPipeline();
  75541. },
  75542. enumerable: true,
  75543. configurable: true
  75544. });
  75545. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75546. get: function () {
  75547. return this._samples;
  75548. },
  75549. /**
  75550. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75551. */
  75552. set: function (sampleCount) {
  75553. if (this._samples === sampleCount) {
  75554. return;
  75555. }
  75556. this._samples = sampleCount;
  75557. this._buildPipeline();
  75558. },
  75559. enumerable: true,
  75560. configurable: true
  75561. });
  75562. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75563. get: function () {
  75564. return this._imageProcessingEnabled;
  75565. },
  75566. /**
  75567. * If image processing is enabled.
  75568. */
  75569. set: function (enabled) {
  75570. if (this._imageProcessingEnabled === enabled) {
  75571. return;
  75572. }
  75573. this._imageProcessingEnabled = enabled;
  75574. this._buildPipeline();
  75575. },
  75576. enumerable: true,
  75577. configurable: true
  75578. });
  75579. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75580. get: function () {
  75581. return this._chromaticAberrationEnabled;
  75582. },
  75583. /**
  75584. * Enable or disable the chromaticAberration process from the pipeline
  75585. */
  75586. set: function (enabled) {
  75587. if (this._chromaticAberrationEnabled === enabled) {
  75588. return;
  75589. }
  75590. this._chromaticAberrationEnabled = enabled;
  75591. this._buildPipeline();
  75592. },
  75593. enumerable: true,
  75594. configurable: true
  75595. });
  75596. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75597. get: function () {
  75598. return this._grainEnabled;
  75599. },
  75600. /**
  75601. * Enable or disable the grain process from the pipeline
  75602. */
  75603. set: function (enabled) {
  75604. if (this._grainEnabled === enabled) {
  75605. return;
  75606. }
  75607. this._grainEnabled = enabled;
  75608. this._buildPipeline();
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. /**
  75614. * Force the compilation of the entire pipeline.
  75615. */
  75616. DefaultRenderingPipeline.prototype.prepare = function () {
  75617. var previousState = this._buildAllowed;
  75618. this._buildAllowed = true;
  75619. this._buildPipeline();
  75620. this._buildAllowed = previousState;
  75621. };
  75622. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75623. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75624. if (this._hasCleared) {
  75625. postProcess.autoClear = false;
  75626. }
  75627. else {
  75628. postProcess.autoClear = true;
  75629. this._scene.autoClear = false;
  75630. this._hasCleared = true;
  75631. }
  75632. if (!skipTextureSharing) {
  75633. if (this._prevPrevPostProcess) {
  75634. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75635. }
  75636. else {
  75637. postProcess.useOwnOutput();
  75638. }
  75639. if (this._prevPostProcess) {
  75640. this._prevPrevPostProcess = this._prevPostProcess;
  75641. }
  75642. this._prevPostProcess = postProcess;
  75643. }
  75644. };
  75645. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75646. var _this = this;
  75647. if (!this._buildAllowed) {
  75648. return;
  75649. }
  75650. this._scene.autoClear = true;
  75651. var engine = this._scene.getEngine();
  75652. this._disposePostProcesses();
  75653. if (this._cameras !== null) {
  75654. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75655. // get back cameras to be used to reattach pipeline
  75656. this._cameras = this._originalCameras.slice();
  75657. }
  75658. this._reset();
  75659. this._prevPostProcess = null;
  75660. this._prevPrevPostProcess = null;
  75661. this._hasCleared = false;
  75662. if (this.depthOfFieldEnabled) {
  75663. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75664. this.depthOfField.depthTexture = depthTexture;
  75665. if (!this.depthOfField._isReady()) {
  75666. this.depthOfField._updateEffects();
  75667. }
  75668. this.addEffect(this.depthOfField);
  75669. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75670. }
  75671. if (this.bloomEnabled) {
  75672. if (!this.bloom._isReady()) {
  75673. this.bloom._updateEffects();
  75674. }
  75675. this.addEffect(this.bloom);
  75676. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75677. }
  75678. if (this._imageProcessingEnabled) {
  75679. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75680. if (this._hdr) {
  75681. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75682. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75683. }
  75684. else {
  75685. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75686. }
  75687. }
  75688. if (this.sharpenEnabled) {
  75689. if (!this.sharpen.isReady()) {
  75690. this.sharpen.updateEffect();
  75691. }
  75692. this.addEffect(this._sharpenEffect);
  75693. this._setAutoClearAndTextureSharing(this.sharpen);
  75694. }
  75695. if (this.grainEnabled) {
  75696. if (!this.grain.isReady()) {
  75697. this.grain.updateEffect();
  75698. }
  75699. this.addEffect(this._grainEffect);
  75700. this._setAutoClearAndTextureSharing(this.grain);
  75701. }
  75702. if (this.chromaticAberrationEnabled) {
  75703. if (!this.chromaticAberration.isReady()) {
  75704. this.chromaticAberration.updateEffect();
  75705. }
  75706. this.addEffect(this._chromaticAberrationEffect);
  75707. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75708. }
  75709. if (this.fxaaEnabled) {
  75710. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75711. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75712. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75713. }
  75714. if (this._cameras !== null) {
  75715. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75716. }
  75717. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75718. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75719. }
  75720. };
  75721. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75722. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75723. for (var i = 0; i < this._cameras.length; i++) {
  75724. var camera = this._cameras[i];
  75725. if (this.imageProcessing) {
  75726. this.imageProcessing.dispose(camera);
  75727. }
  75728. if (this.fxaa) {
  75729. this.fxaa.dispose(camera);
  75730. }
  75731. // These are created in the constructor and should not be disposed on every pipeline change
  75732. if (disposeNonRecreated) {
  75733. if (this.sharpen) {
  75734. this.sharpen.dispose(camera);
  75735. }
  75736. if (this.depthOfField) {
  75737. this.depthOfField.disposeEffects(camera);
  75738. }
  75739. if (this.bloom) {
  75740. this.bloom.disposeEffects(camera);
  75741. }
  75742. if (this.chromaticAberration) {
  75743. this.chromaticAberration.dispose(camera);
  75744. }
  75745. if (this.grain) {
  75746. this.grain.dispose(camera);
  75747. }
  75748. }
  75749. }
  75750. this.imageProcessing = null;
  75751. this.fxaa = null;
  75752. if (disposeNonRecreated) {
  75753. this.sharpen = null;
  75754. this._sharpenEffect = null;
  75755. this.depthOfField = null;
  75756. this.bloom = null;
  75757. this.chromaticAberration = null;
  75758. this._chromaticAberrationEffect = null;
  75759. this.grain = null;
  75760. this._grainEffect = null;
  75761. }
  75762. };
  75763. /**
  75764. * Dispose of the pipeline and stop all post processes
  75765. */
  75766. DefaultRenderingPipeline.prototype.dispose = function () {
  75767. this._disposePostProcesses(true);
  75768. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75769. this._scene.autoClear = true;
  75770. if (this._resizeObserver) {
  75771. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75772. this._resizeObserver = null;
  75773. }
  75774. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75775. _super.prototype.dispose.call(this);
  75776. };
  75777. /**
  75778. * Serialize the rendering pipeline (Used when exporting)
  75779. * @returns the serialized object
  75780. */
  75781. DefaultRenderingPipeline.prototype.serialize = function () {
  75782. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75783. serializationObject.customType = "DefaultRenderingPipeline";
  75784. return serializationObject;
  75785. };
  75786. /**
  75787. * Parse the serialized pipeline
  75788. * @param source Source pipeline.
  75789. * @param scene The scene to load the pipeline to.
  75790. * @param rootUrl The URL of the serialized pipeline.
  75791. * @returns An instantiated pipeline from the serialized object.
  75792. */
  75793. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75794. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75795. };
  75796. __decorate([
  75797. BABYLON.serialize()
  75798. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75799. __decorate([
  75800. BABYLON.serialize()
  75801. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75802. __decorate([
  75803. BABYLON.serialize()
  75804. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75805. __decorate([
  75806. BABYLON.serialize()
  75807. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75808. __decorate([
  75809. BABYLON.serialize()
  75810. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75811. __decorate([
  75812. BABYLON.serialize()
  75813. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75814. __decorate([
  75815. BABYLON.serialize()
  75816. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75817. __decorate([
  75818. BABYLON.serialize()
  75819. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75820. __decorate([
  75821. BABYLON.serialize()
  75822. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75823. __decorate([
  75824. BABYLON.serialize()
  75825. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75826. __decorate([
  75827. BABYLON.serialize()
  75828. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75829. __decorate([
  75830. BABYLON.serialize()
  75831. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75832. __decorate([
  75833. BABYLON.serialize()
  75834. ], DefaultRenderingPipeline.prototype, "samples", null);
  75835. __decorate([
  75836. BABYLON.serialize()
  75837. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75838. __decorate([
  75839. BABYLON.serialize()
  75840. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75841. __decorate([
  75842. BABYLON.serialize()
  75843. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75844. return DefaultRenderingPipeline;
  75845. }(BABYLON.PostProcessRenderPipeline));
  75846. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75847. })(BABYLON || (BABYLON = {}));
  75848. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75849. var BABYLON;
  75850. (function (BABYLON) {
  75851. /**
  75852. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75853. */
  75854. var GeometryBufferRenderer = /** @class */ (function () {
  75855. /**
  75856. * Creates a new G Buffer for the scene
  75857. * @param scene The scene the buffer belongs to
  75858. * @param ratio How big is the buffer related to the main canvas.
  75859. */
  75860. function GeometryBufferRenderer(scene, ratio) {
  75861. if (ratio === void 0) { ratio = 1; }
  75862. this._enablePosition = false;
  75863. this._scene = scene;
  75864. this._ratio = ratio;
  75865. // Render target
  75866. this._createRenderTargets();
  75867. }
  75868. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75869. /**
  75870. * Set the render list (meshes to be rendered) used in the G buffer.
  75871. */
  75872. set: function (meshes) {
  75873. this._multiRenderTarget.renderList = meshes;
  75874. },
  75875. enumerable: true,
  75876. configurable: true
  75877. });
  75878. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75879. /**
  75880. * Gets wether or not G buffer are supported by the running hardware.
  75881. * This requires draw buffer supports
  75882. */
  75883. get: function () {
  75884. return this._multiRenderTarget.isSupported;
  75885. },
  75886. enumerable: true,
  75887. configurable: true
  75888. });
  75889. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75890. /**
  75891. * Gets wether or not position are enabled for the G buffer.
  75892. */
  75893. get: function () {
  75894. return this._enablePosition;
  75895. },
  75896. /**
  75897. * Sets wether or not position are enabled for the G buffer.
  75898. */
  75899. set: function (enable) {
  75900. this._enablePosition = enable;
  75901. this.dispose();
  75902. this._createRenderTargets();
  75903. },
  75904. enumerable: true,
  75905. configurable: true
  75906. });
  75907. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75908. /**
  75909. * Gets the scene associated with the buffer.
  75910. */
  75911. get: function () {
  75912. return this._scene;
  75913. },
  75914. enumerable: true,
  75915. configurable: true
  75916. });
  75917. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75918. /**
  75919. * Gets the ratio used by the buffer during its creation.
  75920. * How big is the buffer related to the main canvas.
  75921. */
  75922. get: function () {
  75923. return this._ratio;
  75924. },
  75925. enumerable: true,
  75926. configurable: true
  75927. });
  75928. /**
  75929. * Checks wether everything is ready to render a submesh to the G buffer.
  75930. * @param subMesh the submesh to check readiness for
  75931. * @param useInstances is the mesh drawn using instance or not
  75932. * @returns true if ready otherwise false
  75933. */
  75934. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75935. var material = subMesh.getMaterial();
  75936. if (material && material.disableDepthWrite) {
  75937. return false;
  75938. }
  75939. var defines = [];
  75940. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75941. var mesh = subMesh.getMesh();
  75942. // Alpha test
  75943. if (material && material.needAlphaTesting()) {
  75944. defines.push("#define ALPHATEST");
  75945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75946. attribs.push(BABYLON.VertexBuffer.UVKind);
  75947. defines.push("#define UV1");
  75948. }
  75949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75950. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75951. defines.push("#define UV2");
  75952. }
  75953. }
  75954. // Buffers
  75955. if (this._enablePosition) {
  75956. defines.push("#define POSITION");
  75957. }
  75958. // Bones
  75959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75962. if (mesh.numBoneInfluencers > 4) {
  75963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75965. }
  75966. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75967. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75968. }
  75969. else {
  75970. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75971. }
  75972. // Instances
  75973. if (useInstances) {
  75974. defines.push("#define INSTANCES");
  75975. attribs.push("world0");
  75976. attribs.push("world1");
  75977. attribs.push("world2");
  75978. attribs.push("world3");
  75979. }
  75980. // Get correct effect
  75981. var join = defines.join("\n");
  75982. if (this._cachedDefines !== join) {
  75983. this._cachedDefines = join;
  75984. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75985. }
  75986. return this._effect.isReady();
  75987. };
  75988. /**
  75989. * Gets the current underlying G Buffer.
  75990. * @returns the buffer
  75991. */
  75992. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75993. return this._multiRenderTarget;
  75994. };
  75995. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75996. /**
  75997. * Gets the number of samples used to render the buffer (anti aliasing).
  75998. */
  75999. get: function () {
  76000. return this._multiRenderTarget.samples;
  76001. },
  76002. /**
  76003. * Sets the number of samples used to render the buffer (anti aliasing).
  76004. */
  76005. set: function (value) {
  76006. this._multiRenderTarget.samples = value;
  76007. },
  76008. enumerable: true,
  76009. configurable: true
  76010. });
  76011. /**
  76012. * Disposes the renderer and frees up associated resources.
  76013. */
  76014. GeometryBufferRenderer.prototype.dispose = function () {
  76015. this.getGBuffer().dispose();
  76016. };
  76017. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76018. var _this = this;
  76019. var engine = this._scene.getEngine();
  76020. var count = this._enablePosition ? 3 : 2;
  76021. 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 });
  76022. if (!this.isSupported) {
  76023. return;
  76024. }
  76025. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76026. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76027. this._multiRenderTarget.refreshRate = 1;
  76028. this._multiRenderTarget.renderParticles = false;
  76029. this._multiRenderTarget.renderList = null;
  76030. // set default depth value to 1.0 (far away)
  76031. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76032. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76033. });
  76034. // Custom render function
  76035. var renderSubMesh = function (subMesh) {
  76036. var mesh = subMesh.getRenderingMesh();
  76037. var scene = _this._scene;
  76038. var engine = scene.getEngine();
  76039. var material = subMesh.getMaterial();
  76040. if (!material) {
  76041. return;
  76042. }
  76043. // Culling
  76044. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76045. // Managing instances
  76046. var batch = mesh._getInstancesRenderList(subMesh._id);
  76047. if (batch.mustReturn) {
  76048. return;
  76049. }
  76050. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76051. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76052. engine.enableEffect(_this._effect);
  76053. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76054. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76055. _this._effect.setMatrix("view", scene.getViewMatrix());
  76056. // Alpha test
  76057. if (material && material.needAlphaTesting()) {
  76058. var alphaTexture = material.getAlphaTestTexture();
  76059. if (alphaTexture) {
  76060. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76061. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76062. }
  76063. }
  76064. // Bones
  76065. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76066. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76067. }
  76068. // Draw
  76069. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76070. }
  76071. };
  76072. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76073. var index;
  76074. if (depthOnlySubMeshes.length) {
  76075. engine.setColorWrite(false);
  76076. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76077. renderSubMesh(depthOnlySubMeshes.data[index]);
  76078. }
  76079. engine.setColorWrite(true);
  76080. }
  76081. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76082. renderSubMesh(opaqueSubMeshes.data[index]);
  76083. }
  76084. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76085. renderSubMesh(alphaTestSubMeshes.data[index]);
  76086. }
  76087. };
  76088. };
  76089. return GeometryBufferRenderer;
  76090. }());
  76091. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76092. })(BABYLON || (BABYLON = {}));
  76093. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76094. var BABYLON;
  76095. (function (BABYLON) {
  76096. var RefractionPostProcess = /** @class */ (function (_super) {
  76097. __extends(RefractionPostProcess, _super);
  76098. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76099. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76100. _this.color = color;
  76101. _this.depth = depth;
  76102. _this.colorLevel = colorLevel;
  76103. _this._ownRefractionTexture = true;
  76104. _this.onActivateObservable.add(function (cam) {
  76105. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76106. });
  76107. _this.onApplyObservable.add(function (effect) {
  76108. effect.setColor3("baseColor", _this.color);
  76109. effect.setFloat("depth", _this.depth);
  76110. effect.setFloat("colorLevel", _this.colorLevel);
  76111. effect.setTexture("refractionSampler", _this._refTexture);
  76112. });
  76113. return _this;
  76114. }
  76115. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76116. /**
  76117. * Gets or sets the refraction texture
  76118. * Please note that you are responsible for disposing the texture if you set it manually
  76119. */
  76120. get: function () {
  76121. return this._refTexture;
  76122. },
  76123. set: function (value) {
  76124. if (this._refTexture && this._ownRefractionTexture) {
  76125. this._refTexture.dispose();
  76126. }
  76127. this._refTexture = value;
  76128. this._ownRefractionTexture = false;
  76129. },
  76130. enumerable: true,
  76131. configurable: true
  76132. });
  76133. // Methods
  76134. RefractionPostProcess.prototype.dispose = function (camera) {
  76135. if (this._refTexture && this._ownRefractionTexture) {
  76136. this._refTexture.dispose();
  76137. this._refTexture = null;
  76138. }
  76139. _super.prototype.dispose.call(this, camera);
  76140. };
  76141. return RefractionPostProcess;
  76142. }(BABYLON.PostProcess));
  76143. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76144. })(BABYLON || (BABYLON = {}));
  76145. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76146. var BABYLON;
  76147. (function (BABYLON) {
  76148. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76149. __extends(BlackAndWhitePostProcess, _super);
  76150. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76151. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76152. _this.degree = 1;
  76153. _this.onApplyObservable.add(function (effect) {
  76154. effect.setFloat("degree", _this.degree);
  76155. });
  76156. return _this;
  76157. }
  76158. return BlackAndWhitePostProcess;
  76159. }(BABYLON.PostProcess));
  76160. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76161. })(BABYLON || (BABYLON = {}));
  76162. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76163. var BABYLON;
  76164. (function (BABYLON) {
  76165. /**
  76166. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76167. * input texture to perform effects such as edge detection or sharpening
  76168. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76169. */
  76170. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76171. __extends(ConvolutionPostProcess, _super);
  76172. /**
  76173. * Creates a new instance ConvolutionPostProcess
  76174. * @param name The name of the effect.
  76175. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76176. * @param options The required width/height ratio to downsize to before computing the render pass.
  76177. * @param camera The camera to apply the render pass to.
  76178. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76179. * @param engine The engine which the post process will be applied. (default: current engine)
  76180. * @param reusable If the post process can be reused on the same frame. (default: false)
  76181. * @param textureType Type of textures used when performing the post process. (default: 0)
  76182. */
  76183. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76184. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76185. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76186. _this.kernel = kernel;
  76187. _this.onApply = function (effect) {
  76188. effect.setFloat2("screenSize", _this.width, _this.height);
  76189. effect.setArray("kernel", _this.kernel);
  76190. };
  76191. return _this;
  76192. }
  76193. // Statics
  76194. /**
  76195. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76196. */
  76197. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76198. /**
  76199. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76200. */
  76201. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76202. /**
  76203. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76204. */
  76205. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76206. /**
  76207. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76208. */
  76209. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76210. /**
  76211. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76212. */
  76213. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76214. /**
  76215. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76216. */
  76217. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76218. return ConvolutionPostProcess;
  76219. }(BABYLON.PostProcess));
  76220. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76221. })(BABYLON || (BABYLON = {}));
  76222. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76223. var BABYLON;
  76224. (function (BABYLON) {
  76225. var FilterPostProcess = /** @class */ (function (_super) {
  76226. __extends(FilterPostProcess, _super);
  76227. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76228. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76229. _this.kernelMatrix = kernelMatrix;
  76230. _this.onApply = function (effect) {
  76231. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76232. };
  76233. return _this;
  76234. }
  76235. return FilterPostProcess;
  76236. }(BABYLON.PostProcess));
  76237. BABYLON.FilterPostProcess = FilterPostProcess;
  76238. })(BABYLON || (BABYLON = {}));
  76239. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76240. var BABYLON;
  76241. (function (BABYLON) {
  76242. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76243. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76244. __extends(VolumetricLightScatteringPostProcess, _super);
  76245. /**
  76246. * @constructor
  76247. * @param {string} name - The post-process name
  76248. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  76249. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76250. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76251. * @param {number} samples - The post-process quality, default 100
  76252. * @param {number} samplingMode - The post-process filtering mode
  76253. * @param {BABYLON.Engine} engine - The babylon engine
  76254. * @param {boolean} reusable - If the post-process is reusable
  76255. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76256. */
  76257. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76258. if (samples === void 0) { samples = 100; }
  76259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76260. 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;
  76261. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76262. /**
  76263. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76264. */
  76265. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76266. /**
  76267. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76268. */
  76269. _this.useCustomMeshPosition = false;
  76270. /**
  76271. * If the post-process should inverse the light scattering direction
  76272. */
  76273. _this.invert = true;
  76274. /**
  76275. * Array containing the excluded meshes not rendered in the internal pass
  76276. */
  76277. _this.excludedMeshes = new Array();
  76278. /**
  76279. * Controls the overall intensity of the post-process
  76280. */
  76281. _this.exposure = 0.3;
  76282. /**
  76283. * Dissipates each sample's contribution in range [0, 1]
  76284. */
  76285. _this.decay = 0.96815;
  76286. /**
  76287. * Controls the overall intensity of each sample
  76288. */
  76289. _this.weight = 0.58767;
  76290. /**
  76291. * Controls the density of each sample
  76292. */
  76293. _this.density = 0.926;
  76294. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76295. engine = scene.getEngine();
  76296. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76297. // Configure mesh
  76298. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76299. // Configure
  76300. _this._createPass(scene, ratio.passRatio || ratio);
  76301. _this.onActivate = function (camera) {
  76302. if (!_this.isSupported) {
  76303. _this.dispose(camera);
  76304. }
  76305. _this.onActivate = null;
  76306. };
  76307. _this.onApplyObservable.add(function (effect) {
  76308. _this._updateMeshScreenCoordinates(scene);
  76309. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76310. effect.setFloat("exposure", _this.exposure);
  76311. effect.setFloat("decay", _this.decay);
  76312. effect.setFloat("weight", _this.weight);
  76313. effect.setFloat("density", _this.density);
  76314. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76315. });
  76316. return _this;
  76317. }
  76318. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76319. get: function () {
  76320. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76321. return false;
  76322. },
  76323. set: function (useDiffuseColor) {
  76324. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76325. },
  76326. enumerable: true,
  76327. configurable: true
  76328. });
  76329. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76330. return "VolumetricLightScatteringPostProcess";
  76331. };
  76332. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76333. var mesh = subMesh.getMesh();
  76334. // Render this.mesh as default
  76335. if (mesh === this.mesh && mesh.material) {
  76336. return mesh.material.isReady(mesh);
  76337. }
  76338. var defines = [];
  76339. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76340. var material = subMesh.getMaterial();
  76341. // Alpha test
  76342. if (material) {
  76343. if (material.needAlphaTesting()) {
  76344. defines.push("#define ALPHATEST");
  76345. }
  76346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76347. attribs.push(BABYLON.VertexBuffer.UVKind);
  76348. defines.push("#define UV1");
  76349. }
  76350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76352. defines.push("#define UV2");
  76353. }
  76354. }
  76355. // Bones
  76356. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76357. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76358. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76359. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76360. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76361. }
  76362. else {
  76363. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76364. }
  76365. // Instances
  76366. if (useInstances) {
  76367. defines.push("#define INSTANCES");
  76368. attribs.push("world0");
  76369. attribs.push("world1");
  76370. attribs.push("world2");
  76371. attribs.push("world3");
  76372. }
  76373. // Get correct effect
  76374. var join = defines.join("\n");
  76375. if (this._cachedDefines !== join) {
  76376. this._cachedDefines = join;
  76377. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76378. }
  76379. return this._volumetricLightScatteringPass.isReady();
  76380. };
  76381. /**
  76382. * Sets the new light position for light scattering effect
  76383. * @param {BABYLON.Vector3} The new custom light position
  76384. */
  76385. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76386. this.customMeshPosition = position;
  76387. };
  76388. /**
  76389. * Returns the light position for light scattering effect
  76390. * @return {BABYLON.Vector3} The custom light position
  76391. */
  76392. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76393. return this.customMeshPosition;
  76394. };
  76395. /**
  76396. * Disposes the internal assets and detaches the post-process from the camera
  76397. */
  76398. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76399. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76400. if (rttIndex !== -1) {
  76401. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76402. }
  76403. this._volumetricLightScatteringRTT.dispose();
  76404. _super.prototype.dispose.call(this, camera);
  76405. };
  76406. /**
  76407. * Returns the render target texture used by the post-process
  76408. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76409. */
  76410. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76411. return this._volumetricLightScatteringRTT;
  76412. };
  76413. // Private methods
  76414. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76415. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76416. return true;
  76417. }
  76418. return false;
  76419. };
  76420. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76421. var _this = this;
  76422. var engine = scene.getEngine();
  76423. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76424. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76425. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76426. this._volumetricLightScatteringRTT.renderList = null;
  76427. this._volumetricLightScatteringRTT.renderParticles = false;
  76428. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76429. var camera = this.getCamera();
  76430. if (camera) {
  76431. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76432. }
  76433. else {
  76434. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76435. }
  76436. // Custom render function for submeshes
  76437. var renderSubMesh = function (subMesh) {
  76438. var mesh = subMesh.getRenderingMesh();
  76439. if (_this._meshExcluded(mesh)) {
  76440. return;
  76441. }
  76442. var material = subMesh.getMaterial();
  76443. if (!material) {
  76444. return;
  76445. }
  76446. var scene = mesh.getScene();
  76447. var engine = scene.getEngine();
  76448. // Culling
  76449. engine.setState(material.backFaceCulling);
  76450. // Managing instances
  76451. var batch = mesh._getInstancesRenderList(subMesh._id);
  76452. if (batch.mustReturn) {
  76453. return;
  76454. }
  76455. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76456. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76457. var effect = _this._volumetricLightScatteringPass;
  76458. if (mesh === _this.mesh) {
  76459. if (subMesh.effect) {
  76460. effect = subMesh.effect;
  76461. }
  76462. else {
  76463. effect = material.getEffect();
  76464. }
  76465. }
  76466. engine.enableEffect(effect);
  76467. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76468. if (mesh === _this.mesh) {
  76469. material.bind(mesh.getWorldMatrix(), mesh);
  76470. }
  76471. else {
  76472. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76473. // Alpha test
  76474. if (material && material.needAlphaTesting()) {
  76475. var alphaTexture = material.getAlphaTestTexture();
  76476. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76477. if (alphaTexture) {
  76478. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76479. }
  76480. }
  76481. // Bones
  76482. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76483. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76484. }
  76485. }
  76486. // Draw
  76487. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76488. }
  76489. };
  76490. // Render target texture callbacks
  76491. var savedSceneClearColor;
  76492. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76493. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76494. savedSceneClearColor = scene.clearColor;
  76495. scene.clearColor = sceneClearColor;
  76496. });
  76497. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76498. scene.clearColor = savedSceneClearColor;
  76499. });
  76500. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76501. var engine = scene.getEngine();
  76502. var index;
  76503. if (depthOnlySubMeshes.length) {
  76504. engine.setColorWrite(false);
  76505. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76506. renderSubMesh(depthOnlySubMeshes.data[index]);
  76507. }
  76508. engine.setColorWrite(true);
  76509. }
  76510. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76511. renderSubMesh(opaqueSubMeshes.data[index]);
  76512. }
  76513. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76514. renderSubMesh(alphaTestSubMeshes.data[index]);
  76515. }
  76516. if (transparentSubMeshes.length) {
  76517. // Sort sub meshes
  76518. for (index = 0; index < transparentSubMeshes.length; index++) {
  76519. var submesh = transparentSubMeshes.data[index];
  76520. var boundingInfo = submesh.getBoundingInfo();
  76521. if (boundingInfo && scene.activeCamera) {
  76522. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76523. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76524. }
  76525. }
  76526. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76527. sortedArray.sort(function (a, b) {
  76528. // Alpha index first
  76529. if (a._alphaIndex > b._alphaIndex) {
  76530. return 1;
  76531. }
  76532. if (a._alphaIndex < b._alphaIndex) {
  76533. return -1;
  76534. }
  76535. // Then distance to camera
  76536. if (a._distanceToCamera < b._distanceToCamera) {
  76537. return 1;
  76538. }
  76539. if (a._distanceToCamera > b._distanceToCamera) {
  76540. return -1;
  76541. }
  76542. return 0;
  76543. });
  76544. // Render sub meshes
  76545. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76546. for (index = 0; index < sortedArray.length; index++) {
  76547. renderSubMesh(sortedArray[index]);
  76548. }
  76549. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76550. }
  76551. };
  76552. };
  76553. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76554. var transform = scene.getTransformMatrix();
  76555. var meshPosition;
  76556. if (this.useCustomMeshPosition) {
  76557. meshPosition = this.customMeshPosition;
  76558. }
  76559. else if (this.attachedNode) {
  76560. meshPosition = this.attachedNode.position;
  76561. }
  76562. else {
  76563. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76564. }
  76565. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76566. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76567. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76568. if (this.invert)
  76569. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76570. };
  76571. // Static methods
  76572. /**
  76573. * Creates a default mesh for the Volumeric Light Scattering post-process
  76574. * @param {string} The mesh name
  76575. * @param {BABYLON.Scene} The scene where to create the mesh
  76576. * @return {BABYLON.Mesh} the default mesh
  76577. */
  76578. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76579. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76580. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76581. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76582. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76583. mesh.material = material;
  76584. return mesh;
  76585. };
  76586. __decorate([
  76587. BABYLON.serializeAsVector3()
  76588. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76589. __decorate([
  76590. BABYLON.serialize()
  76591. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76592. __decorate([
  76593. BABYLON.serialize()
  76594. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76595. __decorate([
  76596. BABYLON.serializeAsMeshReference()
  76597. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76598. __decorate([
  76599. BABYLON.serialize()
  76600. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76601. __decorate([
  76602. BABYLON.serialize()
  76603. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76604. __decorate([
  76605. BABYLON.serialize()
  76606. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76607. __decorate([
  76608. BABYLON.serialize()
  76609. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76610. __decorate([
  76611. BABYLON.serialize()
  76612. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76613. return VolumetricLightScatteringPostProcess;
  76614. }(BABYLON.PostProcess));
  76615. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76616. })(BABYLON || (BABYLON = {}));
  76617. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76618. //
  76619. // This post-process allows the modification of rendered colors by using
  76620. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76621. //
  76622. // The object needs to be provided an url to a texture containing the color
  76623. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76624. // Use an image editing software to tweak the LUT to match your needs.
  76625. //
  76626. // For an example of a color LUT, see here:
  76627. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76628. // For explanations on color grading, see here:
  76629. // http://udn.epicgames.com/Three/ColorGrading.html
  76630. //
  76631. var BABYLON;
  76632. (function (BABYLON) {
  76633. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76634. __extends(ColorCorrectionPostProcess, _super);
  76635. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76636. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76637. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76638. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76639. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76640. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76641. _this.onApply = function (effect) {
  76642. effect.setTexture("colorTable", _this._colorTableTexture);
  76643. };
  76644. return _this;
  76645. }
  76646. return ColorCorrectionPostProcess;
  76647. }(BABYLON.PostProcess));
  76648. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76649. })(BABYLON || (BABYLON = {}));
  76650. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76651. var BABYLON;
  76652. (function (BABYLON) {
  76653. /** Defines operator used for tonemapping */
  76654. var TonemappingOperator;
  76655. (function (TonemappingOperator) {
  76656. /** Hable */
  76657. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76658. /** Reinhard */
  76659. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76660. /** HejiDawson */
  76661. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76662. /** Photographic */
  76663. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76664. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76665. ;
  76666. /**
  76667. * Defines a post process to apply tone mapping
  76668. */
  76669. var TonemapPostProcess = /** @class */ (function (_super) {
  76670. __extends(TonemapPostProcess, _super);
  76671. /**
  76672. * Creates a new TonemapPostProcess
  76673. * @param name defines the name of the postprocess
  76674. * @param _operator defines the operator to use
  76675. * @param exposureAdjustment defines the required exposure adjustement
  76676. * @param camera defines the camera to use (can be null)
  76677. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76678. * @param engine defines the hosting engine (can be ignore if camera is set)
  76679. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76680. */
  76681. function TonemapPostProcess(name, _operator,
  76682. /** Defines the required exposure adjustement */
  76683. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76685. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76686. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76687. _this._operator = _operator;
  76688. _this.exposureAdjustment = exposureAdjustment;
  76689. var defines = "#define ";
  76690. if (_this._operator === TonemappingOperator.Hable)
  76691. defines += "HABLE_TONEMAPPING";
  76692. else if (_this._operator === TonemappingOperator.Reinhard)
  76693. defines += "REINHARD_TONEMAPPING";
  76694. else if (_this._operator === TonemappingOperator.HejiDawson)
  76695. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76696. else if (_this._operator === TonemappingOperator.Photographic)
  76697. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76698. //sadly a second call to create the effect.
  76699. _this.updateEffect(defines);
  76700. _this.onApply = function (effect) {
  76701. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76702. };
  76703. return _this;
  76704. }
  76705. return TonemapPostProcess;
  76706. }(BABYLON.PostProcess));
  76707. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76708. })(BABYLON || (BABYLON = {}));
  76709. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76710. var BABYLON;
  76711. (function (BABYLON) {
  76712. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76713. __extends(DisplayPassPostProcess, _super);
  76714. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76715. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76716. }
  76717. return DisplayPassPostProcess;
  76718. }(BABYLON.PostProcess));
  76719. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76720. })(BABYLON || (BABYLON = {}));
  76721. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76722. var BABYLON;
  76723. (function (BABYLON) {
  76724. var HighlightsPostProcess = /** @class */ (function (_super) {
  76725. __extends(HighlightsPostProcess, _super);
  76726. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76727. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76728. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76729. }
  76730. return HighlightsPostProcess;
  76731. }(BABYLON.PostProcess));
  76732. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76733. })(BABYLON || (BABYLON = {}));
  76734. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76735. var BABYLON;
  76736. (function (BABYLON) {
  76737. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76738. __extends(ImageProcessingPostProcess, _super);
  76739. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76740. if (camera === void 0) { camera = null; }
  76741. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76742. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76743. _this._fromLinearSpace = true;
  76744. /**
  76745. * Defines cache preventing GC.
  76746. */
  76747. _this._defines = {
  76748. IMAGEPROCESSING: false,
  76749. VIGNETTE: false,
  76750. VIGNETTEBLENDMODEMULTIPLY: false,
  76751. VIGNETTEBLENDMODEOPAQUE: false,
  76752. TONEMAPPING: false,
  76753. CONTRAST: false,
  76754. COLORCURVES: false,
  76755. COLORGRADING: false,
  76756. COLORGRADING3D: false,
  76757. FROMLINEARSPACE: false,
  76758. SAMPLER3DGREENDEPTH: false,
  76759. SAMPLER3DBGRMAP: false,
  76760. IMAGEPROCESSINGPOSTPROCESS: false,
  76761. EXPOSURE: false,
  76762. };
  76763. // Setup the configuration as forced by the constructor. This would then not force the
  76764. // scene materials output in linear space and let untouched the default forward pass.
  76765. if (imageProcessingConfiguration) {
  76766. imageProcessingConfiguration.applyByPostProcess = true;
  76767. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76768. // This will cause the shader to be compiled
  76769. _this.fromLinearSpace = false;
  76770. }
  76771. // Setup the default processing configuration to the scene.
  76772. else {
  76773. _this._attachImageProcessingConfiguration(null, true);
  76774. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76775. }
  76776. _this.onApply = function (effect) {
  76777. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76778. };
  76779. return _this;
  76780. }
  76781. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76782. /**
  76783. * Gets the image processing configuration used either in this material.
  76784. */
  76785. get: function () {
  76786. return this._imageProcessingConfiguration;
  76787. },
  76788. /**
  76789. * Sets the Default image processing configuration used either in the this material.
  76790. *
  76791. * If sets to null, the scene one is in use.
  76792. */
  76793. set: function (value) {
  76794. this._attachImageProcessingConfiguration(value);
  76795. },
  76796. enumerable: true,
  76797. configurable: true
  76798. });
  76799. /**
  76800. * Attaches a new image processing configuration to the PBR Material.
  76801. * @param configuration
  76802. */
  76803. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76804. var _this = this;
  76805. if (doNotBuild === void 0) { doNotBuild = false; }
  76806. if (configuration === this._imageProcessingConfiguration) {
  76807. return;
  76808. }
  76809. // Detaches observer.
  76810. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76811. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76812. }
  76813. // Pick the scene configuration if needed.
  76814. if (!configuration) {
  76815. var scene = null;
  76816. var engine = this.getEngine();
  76817. var camera = this.getCamera();
  76818. if (camera) {
  76819. scene = camera.getScene();
  76820. }
  76821. else if (engine && engine.scenes) {
  76822. var scenes = engine.scenes;
  76823. scene = scenes[scenes.length - 1];
  76824. }
  76825. else {
  76826. scene = BABYLON.Engine.LastCreatedScene;
  76827. }
  76828. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76829. }
  76830. else {
  76831. this._imageProcessingConfiguration = configuration;
  76832. }
  76833. // Attaches observer.
  76834. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76835. _this._updateParameters();
  76836. });
  76837. // Ensure the effect will be rebuilt.
  76838. if (!doNotBuild) {
  76839. this._updateParameters();
  76840. }
  76841. };
  76842. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76843. /**
  76844. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76845. */
  76846. get: function () {
  76847. return this.imageProcessingConfiguration.colorCurves;
  76848. },
  76849. /**
  76850. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76851. */
  76852. set: function (value) {
  76853. this.imageProcessingConfiguration.colorCurves = value;
  76854. },
  76855. enumerable: true,
  76856. configurable: true
  76857. });
  76858. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76859. /**
  76860. * Gets wether the color curves effect is enabled.
  76861. */
  76862. get: function () {
  76863. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76864. },
  76865. /**
  76866. * Sets wether the color curves effect is enabled.
  76867. */
  76868. set: function (value) {
  76869. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76870. },
  76871. enumerable: true,
  76872. configurable: true
  76873. });
  76874. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76875. /**
  76876. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76877. */
  76878. get: function () {
  76879. return this.imageProcessingConfiguration.colorGradingTexture;
  76880. },
  76881. /**
  76882. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76883. */
  76884. set: function (value) {
  76885. this.imageProcessingConfiguration.colorGradingTexture = value;
  76886. },
  76887. enumerable: true,
  76888. configurable: true
  76889. });
  76890. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76891. /**
  76892. * Gets wether the color grading effect is enabled.
  76893. */
  76894. get: function () {
  76895. return this.imageProcessingConfiguration.colorGradingEnabled;
  76896. },
  76897. /**
  76898. * Gets wether the color grading effect is enabled.
  76899. */
  76900. set: function (value) {
  76901. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76902. },
  76903. enumerable: true,
  76904. configurable: true
  76905. });
  76906. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76907. /**
  76908. * Gets exposure used in the effect.
  76909. */
  76910. get: function () {
  76911. return this.imageProcessingConfiguration.exposure;
  76912. },
  76913. /**
  76914. * Sets exposure used in the effect.
  76915. */
  76916. set: function (value) {
  76917. this.imageProcessingConfiguration.exposure = value;
  76918. },
  76919. enumerable: true,
  76920. configurable: true
  76921. });
  76922. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76923. /**
  76924. * Gets wether tonemapping is enabled or not.
  76925. */
  76926. get: function () {
  76927. return this._imageProcessingConfiguration.toneMappingEnabled;
  76928. },
  76929. /**
  76930. * Sets wether tonemapping is enabled or not
  76931. */
  76932. set: function (value) {
  76933. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76934. },
  76935. enumerable: true,
  76936. configurable: true
  76937. });
  76938. ;
  76939. ;
  76940. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76941. /**
  76942. * Gets contrast used in the effect.
  76943. */
  76944. get: function () {
  76945. return this.imageProcessingConfiguration.contrast;
  76946. },
  76947. /**
  76948. * Sets contrast used in the effect.
  76949. */
  76950. set: function (value) {
  76951. this.imageProcessingConfiguration.contrast = value;
  76952. },
  76953. enumerable: true,
  76954. configurable: true
  76955. });
  76956. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76957. /**
  76958. * Gets Vignette stretch size.
  76959. */
  76960. get: function () {
  76961. return this.imageProcessingConfiguration.vignetteStretch;
  76962. },
  76963. /**
  76964. * Sets Vignette stretch size.
  76965. */
  76966. set: function (value) {
  76967. this.imageProcessingConfiguration.vignetteStretch = value;
  76968. },
  76969. enumerable: true,
  76970. configurable: true
  76971. });
  76972. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76973. /**
  76974. * Gets Vignette centre X Offset.
  76975. */
  76976. get: function () {
  76977. return this.imageProcessingConfiguration.vignetteCentreX;
  76978. },
  76979. /**
  76980. * Sets Vignette centre X Offset.
  76981. */
  76982. set: function (value) {
  76983. this.imageProcessingConfiguration.vignetteCentreX = value;
  76984. },
  76985. enumerable: true,
  76986. configurable: true
  76987. });
  76988. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76989. /**
  76990. * Gets Vignette centre Y Offset.
  76991. */
  76992. get: function () {
  76993. return this.imageProcessingConfiguration.vignetteCentreY;
  76994. },
  76995. /**
  76996. * Sets Vignette centre Y Offset.
  76997. */
  76998. set: function (value) {
  76999. this.imageProcessingConfiguration.vignetteCentreY = value;
  77000. },
  77001. enumerable: true,
  77002. configurable: true
  77003. });
  77004. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77005. /**
  77006. * Gets Vignette weight or intensity of the vignette effect.
  77007. */
  77008. get: function () {
  77009. return this.imageProcessingConfiguration.vignetteWeight;
  77010. },
  77011. /**
  77012. * Sets Vignette weight or intensity of the vignette effect.
  77013. */
  77014. set: function (value) {
  77015. this.imageProcessingConfiguration.vignetteWeight = value;
  77016. },
  77017. enumerable: true,
  77018. configurable: true
  77019. });
  77020. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77021. /**
  77022. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77023. * if vignetteEnabled is set to true.
  77024. */
  77025. get: function () {
  77026. return this.imageProcessingConfiguration.vignetteColor;
  77027. },
  77028. /**
  77029. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77030. * if vignetteEnabled is set to true.
  77031. */
  77032. set: function (value) {
  77033. this.imageProcessingConfiguration.vignetteColor = value;
  77034. },
  77035. enumerable: true,
  77036. configurable: true
  77037. });
  77038. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77039. /**
  77040. * Gets Camera field of view used by the Vignette effect.
  77041. */
  77042. get: function () {
  77043. return this.imageProcessingConfiguration.vignetteCameraFov;
  77044. },
  77045. /**
  77046. * Sets Camera field of view used by the Vignette effect.
  77047. */
  77048. set: function (value) {
  77049. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77050. },
  77051. enumerable: true,
  77052. configurable: true
  77053. });
  77054. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77055. /**
  77056. * Gets the vignette blend mode allowing different kind of effect.
  77057. */
  77058. get: function () {
  77059. return this.imageProcessingConfiguration.vignetteBlendMode;
  77060. },
  77061. /**
  77062. * Sets the vignette blend mode allowing different kind of effect.
  77063. */
  77064. set: function (value) {
  77065. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77066. },
  77067. enumerable: true,
  77068. configurable: true
  77069. });
  77070. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77071. /**
  77072. * Gets wether the vignette effect is enabled.
  77073. */
  77074. get: function () {
  77075. return this.imageProcessingConfiguration.vignetteEnabled;
  77076. },
  77077. /**
  77078. * Sets wether the vignette effect is enabled.
  77079. */
  77080. set: function (value) {
  77081. this.imageProcessingConfiguration.vignetteEnabled = value;
  77082. },
  77083. enumerable: true,
  77084. configurable: true
  77085. });
  77086. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77087. /**
  77088. * Gets wether the input of the processing is in Gamma or Linear Space.
  77089. */
  77090. get: function () {
  77091. return this._fromLinearSpace;
  77092. },
  77093. /**
  77094. * Sets wether the input of the processing is in Gamma or Linear Space.
  77095. */
  77096. set: function (value) {
  77097. if (this._fromLinearSpace === value) {
  77098. return;
  77099. }
  77100. this._fromLinearSpace = value;
  77101. this._updateParameters();
  77102. },
  77103. enumerable: true,
  77104. configurable: true
  77105. });
  77106. ImageProcessingPostProcess.prototype.getClassName = function () {
  77107. return "ImageProcessingPostProcess";
  77108. };
  77109. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77110. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77111. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77112. var defines = "";
  77113. for (var define in this._defines) {
  77114. if (this._defines[define]) {
  77115. defines += "#define " + define + ";\r\n";
  77116. }
  77117. }
  77118. var samplers = ["textureSampler"];
  77119. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77120. var uniforms = ["scale"];
  77121. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77122. this.updateEffect(defines, uniforms, samplers);
  77123. };
  77124. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77125. _super.prototype.dispose.call(this, camera);
  77126. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77127. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77128. }
  77129. this.imageProcessingConfiguration.applyByPostProcess = false;
  77130. };
  77131. __decorate([
  77132. BABYLON.serialize()
  77133. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77134. return ImageProcessingPostProcess;
  77135. }(BABYLON.PostProcess));
  77136. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77137. })(BABYLON || (BABYLON = {}));
  77138. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77139. var BABYLON;
  77140. (function (BABYLON) {
  77141. /**
  77142. * Class used to store bone information
  77143. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77144. */
  77145. var Bone = /** @class */ (function (_super) {
  77146. __extends(Bone, _super);
  77147. /**
  77148. * Create a new bone
  77149. * @param name defines the bone name
  77150. * @param skeleton defines the parent skeleton
  77151. * @param parentBone defines the parent (can be null if the bone is the root)
  77152. * @param localMatrix defines the local matrix
  77153. * @param restPose defines the rest pose matrix
  77154. * @param baseMatrix defines the base matrix
  77155. * @param index defines index of the bone in the hiearchy
  77156. */
  77157. function Bone(
  77158. /**
  77159. * defines the bone name
  77160. */
  77161. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77162. if (parentBone === void 0) { parentBone = null; }
  77163. if (localMatrix === void 0) { localMatrix = null; }
  77164. if (restPose === void 0) { restPose = null; }
  77165. if (baseMatrix === void 0) { baseMatrix = null; }
  77166. if (index === void 0) { index = null; }
  77167. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77168. _this.name = name;
  77169. /**
  77170. * Gets the list of child bones
  77171. */
  77172. _this.children = new Array();
  77173. /** Gets the animations associated with this bone */
  77174. _this.animations = new Array();
  77175. /**
  77176. * @hidden Internal only
  77177. * Set this value to map this bone to a different index in the transform matrices
  77178. * Set this value to -1 to exclude the bone from the transform matrices
  77179. */
  77180. _this._index = null;
  77181. _this._absoluteTransform = new BABYLON.Matrix();
  77182. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77183. _this._scalingDeterminant = 1;
  77184. _this._worldTransform = new BABYLON.Matrix();
  77185. _this._needToDecompose = true;
  77186. _this._needToCompose = false;
  77187. _this._skeleton = skeleton;
  77188. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77189. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77190. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77191. _this._index = index;
  77192. skeleton.bones.push(_this);
  77193. _this.setParent(parentBone, false);
  77194. if (baseMatrix || localMatrix) {
  77195. _this._updateDifferenceMatrix();
  77196. }
  77197. return _this;
  77198. }
  77199. Object.defineProperty(Bone.prototype, "_matrix", {
  77200. /** @hidden */
  77201. get: function () {
  77202. this._compose();
  77203. return this._localMatrix;
  77204. },
  77205. /** @hidden */
  77206. set: function (value) {
  77207. this._localMatrix.copyFrom(value);
  77208. this._needToDecompose = true;
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. // Members
  77214. /**
  77215. * Gets the parent skeleton
  77216. * @returns a skeleton
  77217. */
  77218. Bone.prototype.getSkeleton = function () {
  77219. return this._skeleton;
  77220. };
  77221. /**
  77222. * Gets parent bone
  77223. * @returns a bone or null if the bone is the root of the bone hierarchy
  77224. */
  77225. Bone.prototype.getParent = function () {
  77226. return this._parent;
  77227. };
  77228. /**
  77229. * Sets the parent bone
  77230. * @param parent defines the parent (can be null if the bone is the root)
  77231. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77232. */
  77233. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77234. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77235. if (this._parent === parent) {
  77236. return;
  77237. }
  77238. if (this._parent) {
  77239. var index = this._parent.children.indexOf(this);
  77240. if (index !== -1) {
  77241. this._parent.children.splice(index, 1);
  77242. }
  77243. }
  77244. this._parent = parent;
  77245. if (this._parent) {
  77246. this._parent.children.push(this);
  77247. }
  77248. if (updateDifferenceMatrix) {
  77249. this._updateDifferenceMatrix();
  77250. }
  77251. this.markAsDirty();
  77252. };
  77253. /**
  77254. * Gets the local matrix
  77255. * @returns a matrix
  77256. */
  77257. Bone.prototype.getLocalMatrix = function () {
  77258. this._compose();
  77259. return this._localMatrix;
  77260. };
  77261. /**
  77262. * Gets the base matrix (initial matrix which remains unchanged)
  77263. * @returns a matrix
  77264. */
  77265. Bone.prototype.getBaseMatrix = function () {
  77266. return this._baseMatrix;
  77267. };
  77268. /**
  77269. * Gets the rest pose matrix
  77270. * @returns a matrix
  77271. */
  77272. Bone.prototype.getRestPose = function () {
  77273. return this._restPose;
  77274. };
  77275. /**
  77276. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77277. */
  77278. Bone.prototype.getWorldMatrix = function () {
  77279. return this._worldTransform;
  77280. };
  77281. /**
  77282. * Sets the local matrix to rest pose matrix
  77283. */
  77284. Bone.prototype.returnToRest = function () {
  77285. this.updateMatrix(this._restPose.clone());
  77286. };
  77287. /**
  77288. * Gets the inverse of the absolute transform matrix.
  77289. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77290. * @returns a matrix
  77291. */
  77292. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77293. return this._invertedAbsoluteTransform;
  77294. };
  77295. /**
  77296. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77297. * @returns a matrix
  77298. */
  77299. Bone.prototype.getAbsoluteTransform = function () {
  77300. return this._absoluteTransform;
  77301. };
  77302. Object.defineProperty(Bone.prototype, "position", {
  77303. // Properties (matches AbstractMesh properties)
  77304. /** Gets or sets current position (in local space) */
  77305. get: function () {
  77306. this._decompose();
  77307. return this._localPosition;
  77308. },
  77309. set: function (newPosition) {
  77310. this._decompose();
  77311. this._localPosition.copyFrom(newPosition);
  77312. this._markAsDirtyAndCompose();
  77313. },
  77314. enumerable: true,
  77315. configurable: true
  77316. });
  77317. Object.defineProperty(Bone.prototype, "rotation", {
  77318. /** Gets or sets current rotation (in local space) */
  77319. get: function () {
  77320. return this.getRotation();
  77321. },
  77322. set: function (newRotation) {
  77323. this.setRotation(newRotation);
  77324. },
  77325. enumerable: true,
  77326. configurable: true
  77327. });
  77328. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77329. /** Gets or sets current rotation quaternion (in local space) */
  77330. get: function () {
  77331. this._decompose();
  77332. return this._localRotation;
  77333. },
  77334. set: function (newRotation) {
  77335. this.setRotationQuaternion(newRotation);
  77336. },
  77337. enumerable: true,
  77338. configurable: true
  77339. });
  77340. Object.defineProperty(Bone.prototype, "scaling", {
  77341. /** Gets or sets current scaling (in local space) */
  77342. get: function () {
  77343. return this.getScale();
  77344. },
  77345. set: function (newScaling) {
  77346. this.setScale(newScaling);
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77352. /**
  77353. * Gets the animation properties override
  77354. */
  77355. get: function () {
  77356. return this._skeleton.animationPropertiesOverride;
  77357. },
  77358. enumerable: true,
  77359. configurable: true
  77360. });
  77361. // Methods
  77362. Bone.prototype._decompose = function () {
  77363. if (!this._needToDecompose) {
  77364. return;
  77365. }
  77366. this._needToDecompose = false;
  77367. if (!this._localScaling) {
  77368. this._localScaling = BABYLON.Vector3.Zero();
  77369. this._localRotation = BABYLON.Quaternion.Zero();
  77370. this._localPosition = BABYLON.Vector3.Zero();
  77371. }
  77372. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77373. };
  77374. Bone.prototype._compose = function () {
  77375. if (!this._needToCompose) {
  77376. return;
  77377. }
  77378. this._needToCompose = false;
  77379. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77380. };
  77381. /**
  77382. * Update the base and local matrices
  77383. * @param matrix defines the new base or local matrix
  77384. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77385. * @param updateLocalMatrix defines if the local matrix should be updated
  77386. */
  77387. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77388. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77389. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77390. this._baseMatrix.copyFrom(matrix);
  77391. if (updateDifferenceMatrix) {
  77392. this._updateDifferenceMatrix();
  77393. }
  77394. if (updateLocalMatrix) {
  77395. this._localMatrix.copyFrom(matrix);
  77396. this._markAsDirtyAndDecompose();
  77397. }
  77398. else {
  77399. this.markAsDirty();
  77400. }
  77401. };
  77402. /** @hidden */
  77403. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77404. if (updateChildren === void 0) { updateChildren = true; }
  77405. if (!rootMatrix) {
  77406. rootMatrix = this._baseMatrix;
  77407. }
  77408. if (this._parent) {
  77409. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77410. }
  77411. else {
  77412. this._absoluteTransform.copyFrom(rootMatrix);
  77413. }
  77414. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77415. if (updateChildren) {
  77416. for (var index = 0; index < this.children.length; index++) {
  77417. this.children[index]._updateDifferenceMatrix();
  77418. }
  77419. }
  77420. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77421. };
  77422. /**
  77423. * Flag the bone as dirty (Forcing it to update everything)
  77424. */
  77425. Bone.prototype.markAsDirty = function () {
  77426. this._currentRenderId++;
  77427. this._childRenderId++;
  77428. this._skeleton._markAsDirty();
  77429. };
  77430. Bone.prototype._markAsDirtyAndCompose = function () {
  77431. this.markAsDirty();
  77432. this._needToCompose = true;
  77433. };
  77434. Bone.prototype._markAsDirtyAndDecompose = function () {
  77435. this.markAsDirty();
  77436. this._needToDecompose = true;
  77437. };
  77438. /**
  77439. * Copy an animation range from another bone
  77440. * @param source defines the source bone
  77441. * @param rangeName defines the range name to copy
  77442. * @param frameOffset defines the frame offset
  77443. * @param rescaleAsRequired defines if rescaling must be applied if required
  77444. * @param skelDimensionsRatio defines the scaling ratio
  77445. * @returns true if operation was successful
  77446. */
  77447. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77448. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77449. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77450. // all animation may be coming from a library skeleton, so may need to create animation
  77451. if (this.animations.length === 0) {
  77452. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77453. this.animations[0].setKeys([]);
  77454. }
  77455. // get animation info / verify there is such a range from the source bone
  77456. var sourceRange = source.animations[0].getRange(rangeName);
  77457. if (!sourceRange) {
  77458. return false;
  77459. }
  77460. var from = sourceRange.from;
  77461. var to = sourceRange.to;
  77462. var sourceKeys = source.animations[0].getKeys();
  77463. // rescaling prep
  77464. var sourceBoneLength = source.length;
  77465. var sourceParent = source.getParent();
  77466. var parent = this.getParent();
  77467. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77468. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77469. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77470. var destKeys = this.animations[0].getKeys();
  77471. // loop vars declaration
  77472. var orig;
  77473. var origTranslation;
  77474. var mat;
  77475. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77476. orig = sourceKeys[key];
  77477. if (orig.frame >= from && orig.frame <= to) {
  77478. if (rescaleAsRequired) {
  77479. mat = orig.value.clone();
  77480. // scale based on parent ratio, when bone has parent
  77481. if (parentScalingReqd) {
  77482. origTranslation = mat.getTranslation();
  77483. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77484. // scale based on skeleton dimension ratio when root bone, and value is passed
  77485. }
  77486. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77487. origTranslation = mat.getTranslation();
  77488. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77489. // use original when root bone, and no data for skelDimensionsRatio
  77490. }
  77491. else {
  77492. mat = orig.value;
  77493. }
  77494. }
  77495. else {
  77496. mat = orig.value;
  77497. }
  77498. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77499. }
  77500. }
  77501. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77502. return true;
  77503. };
  77504. /**
  77505. * Translate the bone in local or world space
  77506. * @param vec The amount to translate the bone
  77507. * @param space The space that the translation is in
  77508. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77509. */
  77510. Bone.prototype.translate = function (vec, space, mesh) {
  77511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77512. var lm = this.getLocalMatrix();
  77513. if (space == BABYLON.Space.LOCAL) {
  77514. lm.m[12] += vec.x;
  77515. lm.m[13] += vec.y;
  77516. lm.m[14] += vec.z;
  77517. }
  77518. else {
  77519. var wm = null;
  77520. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77521. if (mesh) {
  77522. wm = mesh.getWorldMatrix();
  77523. }
  77524. this._skeleton.computeAbsoluteTransforms();
  77525. var tmat = Bone._tmpMats[0];
  77526. var tvec = Bone._tmpVecs[0];
  77527. if (this._parent) {
  77528. if (mesh && wm) {
  77529. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77530. tmat.multiplyToRef(wm, tmat);
  77531. }
  77532. else {
  77533. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77534. }
  77535. }
  77536. tmat.m[12] = 0;
  77537. tmat.m[13] = 0;
  77538. tmat.m[14] = 0;
  77539. tmat.invert();
  77540. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77541. lm.m[12] += tvec.x;
  77542. lm.m[13] += tvec.y;
  77543. lm.m[14] += tvec.z;
  77544. }
  77545. this._markAsDirtyAndDecompose();
  77546. };
  77547. /**
  77548. * Set the postion of the bone in local or world space
  77549. * @param position The position to set the bone
  77550. * @param space The space that the position is in
  77551. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77552. */
  77553. Bone.prototype.setPosition = function (position, space, mesh) {
  77554. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77555. var lm = this.getLocalMatrix();
  77556. if (space == BABYLON.Space.LOCAL) {
  77557. lm.m[12] = position.x;
  77558. lm.m[13] = position.y;
  77559. lm.m[14] = position.z;
  77560. }
  77561. else {
  77562. var wm = null;
  77563. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77564. if (mesh) {
  77565. wm = mesh.getWorldMatrix();
  77566. }
  77567. this._skeleton.computeAbsoluteTransforms();
  77568. var tmat = Bone._tmpMats[0];
  77569. var vec = Bone._tmpVecs[0];
  77570. if (this._parent) {
  77571. if (mesh && wm) {
  77572. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77573. tmat.multiplyToRef(wm, tmat);
  77574. }
  77575. else {
  77576. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77577. }
  77578. }
  77579. tmat.invert();
  77580. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77581. lm.m[12] = vec.x;
  77582. lm.m[13] = vec.y;
  77583. lm.m[14] = vec.z;
  77584. }
  77585. this._markAsDirtyAndDecompose();
  77586. };
  77587. /**
  77588. * Set the absolute position of the bone (world space)
  77589. * @param position The position to set the bone
  77590. * @param mesh The mesh that this bone is attached to
  77591. */
  77592. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77593. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77594. };
  77595. /**
  77596. * Scale the bone on the x, y and z axes (in local space)
  77597. * @param x The amount to scale the bone on the x axis
  77598. * @param y The amount to scale the bone on the y axis
  77599. * @param z The amount to scale the bone on the z axis
  77600. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77601. */
  77602. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77603. if (scaleChildren === void 0) { scaleChildren = false; }
  77604. var locMat = this.getLocalMatrix();
  77605. // Apply new scaling on top of current local matrix
  77606. var scaleMat = Bone._tmpMats[0];
  77607. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77608. scaleMat.multiplyToRef(locMat, locMat);
  77609. // Invert scaling matrix and apply the inverse to all children
  77610. scaleMat.invert();
  77611. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77612. var child = _a[_i];
  77613. var cm = child.getLocalMatrix();
  77614. cm.multiplyToRef(scaleMat, cm);
  77615. cm.m[12] *= x;
  77616. cm.m[13] *= y;
  77617. cm.m[14] *= z;
  77618. child._markAsDirtyAndDecompose();
  77619. }
  77620. this._markAsDirtyAndDecompose();
  77621. if (scaleChildren) {
  77622. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77623. var child = _c[_b];
  77624. child.scale(x, y, z, scaleChildren);
  77625. }
  77626. }
  77627. };
  77628. /**
  77629. * Set the bone scaling in local space
  77630. * @param scale defines the scaling vector
  77631. */
  77632. Bone.prototype.setScale = function (scale) {
  77633. this._decompose();
  77634. this._localScaling.copyFrom(scale);
  77635. this._markAsDirtyAndCompose();
  77636. };
  77637. /**
  77638. * Gets the current scaling in local space
  77639. * @returns the current scaling vector
  77640. */
  77641. Bone.prototype.getScale = function () {
  77642. this._decompose();
  77643. return this._localScaling;
  77644. };
  77645. /**
  77646. * Gets the current scaling in local space and stores it in a target vector
  77647. * @param result defines the target vector
  77648. */
  77649. Bone.prototype.getScaleToRef = function (result) {
  77650. this._decompose();
  77651. result.copyFrom(this._localScaling);
  77652. };
  77653. /**
  77654. * Set the yaw, pitch, and roll of the bone in local or world space
  77655. * @param yaw The rotation of the bone on the y axis
  77656. * @param pitch The rotation of the bone on the x axis
  77657. * @param roll The rotation of the bone on the z axis
  77658. * @param space The space that the axes of rotation are in
  77659. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77660. */
  77661. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77663. if (space === BABYLON.Space.LOCAL) {
  77664. var quat = Bone._tmpQuat;
  77665. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77666. this.setRotationQuaternion(quat, space, mesh);
  77667. return;
  77668. }
  77669. var rotMatInv = Bone._tmpMats[0];
  77670. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77671. return;
  77672. }
  77673. var rotMat = Bone._tmpMats[1];
  77674. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77675. rotMatInv.multiplyToRef(rotMat, rotMat);
  77676. this._rotateWithMatrix(rotMat, space, mesh);
  77677. };
  77678. /**
  77679. * Add a rotation to the bone on an axis in local or world space
  77680. * @param axis The axis to rotate the bone on
  77681. * @param amount The amount to rotate the bone
  77682. * @param space The space that the axis is in
  77683. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77684. */
  77685. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77687. var rmat = Bone._tmpMats[0];
  77688. rmat.m[12] = 0;
  77689. rmat.m[13] = 0;
  77690. rmat.m[14] = 0;
  77691. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77692. this._rotateWithMatrix(rmat, space, mesh);
  77693. };
  77694. /**
  77695. * Set the rotation of the bone to a particular axis angle in local or world space
  77696. * @param axis The axis to rotate the bone on
  77697. * @param angle The angle that the bone should be rotated to
  77698. * @param space The space that the axis is in
  77699. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77700. */
  77701. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77702. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77703. if (space === BABYLON.Space.LOCAL) {
  77704. var quat = Bone._tmpQuat;
  77705. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77706. this.setRotationQuaternion(quat, space, mesh);
  77707. return;
  77708. }
  77709. var rotMatInv = Bone._tmpMats[0];
  77710. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77711. return;
  77712. }
  77713. var rotMat = Bone._tmpMats[1];
  77714. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77715. rotMatInv.multiplyToRef(rotMat, rotMat);
  77716. this._rotateWithMatrix(rotMat, space, mesh);
  77717. };
  77718. /**
  77719. * Set the euler rotation of the bone in local of world space
  77720. * @param rotation The euler rotation that the bone should be set to
  77721. * @param space The space that the rotation is in
  77722. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77723. */
  77724. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77725. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77726. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77727. };
  77728. /**
  77729. * Set the quaternion rotation of the bone in local of world space
  77730. * @param quat The quaternion rotation that the bone should be set to
  77731. * @param space The space that the rotation is in
  77732. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77733. */
  77734. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77736. if (space === BABYLON.Space.LOCAL) {
  77737. this._decompose();
  77738. this._localRotation.copyFrom(quat);
  77739. this._markAsDirtyAndCompose();
  77740. return;
  77741. }
  77742. var rotMatInv = Bone._tmpMats[0];
  77743. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77744. return;
  77745. }
  77746. var rotMat = Bone._tmpMats[1];
  77747. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77748. rotMatInv.multiplyToRef(rotMat, rotMat);
  77749. this._rotateWithMatrix(rotMat, space, mesh);
  77750. };
  77751. /**
  77752. * Set the rotation matrix of the bone in local of world space
  77753. * @param rotMat The rotation matrix that the bone should be set to
  77754. * @param space The space that the rotation is in
  77755. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77756. */
  77757. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77759. if (space === BABYLON.Space.LOCAL) {
  77760. var quat = Bone._tmpQuat;
  77761. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77762. this.setRotationQuaternion(quat, space, mesh);
  77763. return;
  77764. }
  77765. var rotMatInv = Bone._tmpMats[0];
  77766. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77767. return;
  77768. }
  77769. var rotMat2 = Bone._tmpMats[1];
  77770. rotMat2.copyFrom(rotMat);
  77771. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77772. this._rotateWithMatrix(rotMat2, space, mesh);
  77773. };
  77774. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77776. var lmat = this.getLocalMatrix();
  77777. var lx = lmat.m[12];
  77778. var ly = lmat.m[13];
  77779. var lz = lmat.m[14];
  77780. var parent = this.getParent();
  77781. var parentScale = Bone._tmpMats[3];
  77782. var parentScaleInv = Bone._tmpMats[4];
  77783. if (parent && space == BABYLON.Space.WORLD) {
  77784. if (mesh) {
  77785. parentScale.copyFrom(mesh.getWorldMatrix());
  77786. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77787. }
  77788. else {
  77789. parentScale.copyFrom(parent.getAbsoluteTransform());
  77790. }
  77791. parentScaleInv.copyFrom(parentScale);
  77792. parentScaleInv.invert();
  77793. lmat.multiplyToRef(parentScale, lmat);
  77794. lmat.multiplyToRef(rmat, lmat);
  77795. lmat.multiplyToRef(parentScaleInv, lmat);
  77796. }
  77797. else {
  77798. if (space == BABYLON.Space.WORLD && mesh) {
  77799. parentScale.copyFrom(mesh.getWorldMatrix());
  77800. parentScaleInv.copyFrom(parentScale);
  77801. parentScaleInv.invert();
  77802. lmat.multiplyToRef(parentScale, lmat);
  77803. lmat.multiplyToRef(rmat, lmat);
  77804. lmat.multiplyToRef(parentScaleInv, lmat);
  77805. }
  77806. else {
  77807. lmat.multiplyToRef(rmat, lmat);
  77808. }
  77809. }
  77810. lmat.m[12] = lx;
  77811. lmat.m[13] = ly;
  77812. lmat.m[14] = lz;
  77813. this.computeAbsoluteTransforms();
  77814. this._markAsDirtyAndDecompose();
  77815. };
  77816. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77817. var scaleMatrix = Bone._tmpMats[2];
  77818. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77819. if (mesh) {
  77820. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77821. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77822. }
  77823. rotMatInv.invert();
  77824. if (isNaN(rotMatInv.m[0])) {
  77825. // Matrix failed to invert.
  77826. // This can happen if scale is zero for example.
  77827. return false;
  77828. }
  77829. scaleMatrix.m[0] *= this._scalingDeterminant;
  77830. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77831. return true;
  77832. };
  77833. /**
  77834. * Get the position of the bone in local or world space
  77835. * @param space The space that the returned position is in
  77836. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77837. * @returns The position of the bone
  77838. */
  77839. Bone.prototype.getPosition = function (space, mesh) {
  77840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77841. if (mesh === void 0) { mesh = null; }
  77842. var pos = BABYLON.Vector3.Zero();
  77843. this.getPositionToRef(space, mesh, pos);
  77844. return pos;
  77845. };
  77846. /**
  77847. * Copy the position of the bone to a vector3 in local or world space
  77848. * @param space The space that the returned position is in
  77849. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77850. * @param result The vector3 to copy the position to
  77851. */
  77852. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77854. if (space == BABYLON.Space.LOCAL) {
  77855. var lm = this.getLocalMatrix();
  77856. result.x = lm.m[12];
  77857. result.y = lm.m[13];
  77858. result.z = lm.m[14];
  77859. }
  77860. else {
  77861. var wm = null;
  77862. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77863. if (mesh) {
  77864. wm = mesh.getWorldMatrix();
  77865. }
  77866. this._skeleton.computeAbsoluteTransforms();
  77867. var tmat = Bone._tmpMats[0];
  77868. if (mesh && wm) {
  77869. tmat.copyFrom(this.getAbsoluteTransform());
  77870. tmat.multiplyToRef(wm, tmat);
  77871. }
  77872. else {
  77873. tmat = this.getAbsoluteTransform();
  77874. }
  77875. result.x = tmat.m[12];
  77876. result.y = tmat.m[13];
  77877. result.z = tmat.m[14];
  77878. }
  77879. };
  77880. /**
  77881. * Get the absolute position of the bone (world space)
  77882. * @param mesh The mesh that this bone is attached to
  77883. * @returns The absolute position of the bone
  77884. */
  77885. Bone.prototype.getAbsolutePosition = function (mesh) {
  77886. if (mesh === void 0) { mesh = null; }
  77887. var pos = BABYLON.Vector3.Zero();
  77888. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77889. return pos;
  77890. };
  77891. /**
  77892. * Copy the absolute position of the bone (world space) to the result param
  77893. * @param mesh The mesh that this bone is attached to
  77894. * @param result The vector3 to copy the absolute position to
  77895. */
  77896. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77897. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77898. };
  77899. /**
  77900. * Compute the absolute transforms of this bone and its children
  77901. */
  77902. Bone.prototype.computeAbsoluteTransforms = function () {
  77903. this._compose();
  77904. if (this._parent) {
  77905. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77906. }
  77907. else {
  77908. this._absoluteTransform.copyFrom(this._localMatrix);
  77909. var poseMatrix = this._skeleton.getPoseMatrix();
  77910. if (poseMatrix) {
  77911. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77912. }
  77913. }
  77914. var children = this.children;
  77915. var len = children.length;
  77916. for (var i = 0; i < len; i++) {
  77917. children[i].computeAbsoluteTransforms();
  77918. }
  77919. };
  77920. /**
  77921. * Get the world direction from an axis that is in the local space of the bone
  77922. * @param localAxis The local direction that is used to compute the world direction
  77923. * @param mesh The mesh that this bone is attached to
  77924. * @returns The world direction
  77925. */
  77926. Bone.prototype.getDirection = function (localAxis, mesh) {
  77927. if (mesh === void 0) { mesh = null; }
  77928. var result = BABYLON.Vector3.Zero();
  77929. this.getDirectionToRef(localAxis, mesh, result);
  77930. return result;
  77931. };
  77932. /**
  77933. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77934. * @param localAxis The local direction that is used to compute the world direction
  77935. * @param mesh The mesh that this bone is attached to
  77936. * @param result The vector3 that the world direction will be copied to
  77937. */
  77938. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77939. if (mesh === void 0) { mesh = null; }
  77940. var wm = null;
  77941. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77942. if (mesh) {
  77943. wm = mesh.getWorldMatrix();
  77944. }
  77945. this._skeleton.computeAbsoluteTransforms();
  77946. var mat = Bone._tmpMats[0];
  77947. mat.copyFrom(this.getAbsoluteTransform());
  77948. if (mesh && wm) {
  77949. mat.multiplyToRef(wm, mat);
  77950. }
  77951. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77952. result.normalize();
  77953. };
  77954. /**
  77955. * Get the euler rotation of the bone in local or world space
  77956. * @param space The space that the rotation should be in
  77957. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77958. * @returns The euler rotation
  77959. */
  77960. Bone.prototype.getRotation = function (space, mesh) {
  77961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77962. if (mesh === void 0) { mesh = null; }
  77963. var result = BABYLON.Vector3.Zero();
  77964. this.getRotationToRef(space, mesh, result);
  77965. return result;
  77966. };
  77967. /**
  77968. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77969. * @param space The space that the rotation should be in
  77970. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77971. * @param result The vector3 that the rotation should be copied to
  77972. */
  77973. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  77974. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77975. if (mesh === void 0) { mesh = null; }
  77976. var quat = Bone._tmpQuat;
  77977. this.getRotationQuaternionToRef(space, mesh, quat);
  77978. quat.toEulerAnglesToRef(result);
  77979. };
  77980. /**
  77981. * Get the quaternion rotation of the bone in either local or world space
  77982. * @param space The space that the rotation should be in
  77983. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77984. * @returns The quaternion rotation
  77985. */
  77986. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  77987. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77988. if (mesh === void 0) { mesh = null; }
  77989. var result = BABYLON.Quaternion.Identity();
  77990. this.getRotationQuaternionToRef(space, mesh, result);
  77991. return result;
  77992. };
  77993. /**
  77994. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  77995. * @param space The space that the rotation should be in
  77996. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77997. * @param result The quaternion that the rotation should be copied to
  77998. */
  77999. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78001. if (mesh === void 0) { mesh = null; }
  78002. if (space == BABYLON.Space.LOCAL) {
  78003. this._decompose();
  78004. result.copyFrom(this._localRotation);
  78005. }
  78006. else {
  78007. var mat = Bone._tmpMats[0];
  78008. var amat = this.getAbsoluteTransform();
  78009. if (mesh) {
  78010. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78011. }
  78012. else {
  78013. mat.copyFrom(amat);
  78014. }
  78015. mat.m[0] *= this._scalingDeterminant;
  78016. mat.m[1] *= this._scalingDeterminant;
  78017. mat.m[2] *= this._scalingDeterminant;
  78018. mat.decompose(undefined, result, undefined);
  78019. }
  78020. };
  78021. /**
  78022. * Get the rotation matrix of the bone in local or world space
  78023. * @param space The space that the rotation should be in
  78024. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78025. * @returns The rotation matrix
  78026. */
  78027. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78028. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78029. var result = BABYLON.Matrix.Identity();
  78030. this.getRotationMatrixToRef(space, mesh, result);
  78031. return result;
  78032. };
  78033. /**
  78034. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78035. * @param space The space that the rotation should be in
  78036. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78037. * @param result The quaternion that the rotation should be copied to
  78038. */
  78039. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78041. if (space == BABYLON.Space.LOCAL) {
  78042. this.getLocalMatrix().getRotationMatrixToRef(result);
  78043. }
  78044. else {
  78045. var mat = Bone._tmpMats[0];
  78046. var amat = this.getAbsoluteTransform();
  78047. if (mesh) {
  78048. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78049. }
  78050. else {
  78051. mat.copyFrom(amat);
  78052. }
  78053. mat.m[0] *= this._scalingDeterminant;
  78054. mat.m[1] *= this._scalingDeterminant;
  78055. mat.m[2] *= this._scalingDeterminant;
  78056. mat.getRotationMatrixToRef(result);
  78057. }
  78058. };
  78059. /**
  78060. * Get the world position of a point that is in the local space of the bone
  78061. * @param position The local position
  78062. * @param mesh The mesh that this bone is attached to
  78063. * @returns The world position
  78064. */
  78065. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78066. if (mesh === void 0) { mesh = null; }
  78067. var result = BABYLON.Vector3.Zero();
  78068. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78069. return result;
  78070. };
  78071. /**
  78072. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78073. * @param position The local position
  78074. * @param mesh The mesh that this bone is attached to
  78075. * @param result The vector3 that the world position should be copied to
  78076. */
  78077. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78078. if (mesh === void 0) { mesh = null; }
  78079. var wm = null;
  78080. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78081. if (mesh) {
  78082. wm = mesh.getWorldMatrix();
  78083. }
  78084. this._skeleton.computeAbsoluteTransforms();
  78085. var tmat = Bone._tmpMats[0];
  78086. if (mesh && wm) {
  78087. tmat.copyFrom(this.getAbsoluteTransform());
  78088. tmat.multiplyToRef(wm, tmat);
  78089. }
  78090. else {
  78091. tmat = this.getAbsoluteTransform();
  78092. }
  78093. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78094. };
  78095. /**
  78096. * Get the local position of a point that is in world space
  78097. * @param position The world position
  78098. * @param mesh The mesh that this bone is attached to
  78099. * @returns The local position
  78100. */
  78101. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78102. if (mesh === void 0) { mesh = null; }
  78103. var result = BABYLON.Vector3.Zero();
  78104. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78105. return result;
  78106. };
  78107. /**
  78108. * Get the local position of a point that is in world space and copy it to the result param
  78109. * @param position The world position
  78110. * @param mesh The mesh that this bone is attached to
  78111. * @param result The vector3 that the local position should be copied to
  78112. */
  78113. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78114. if (mesh === void 0) { mesh = null; }
  78115. var wm = null;
  78116. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78117. if (mesh) {
  78118. wm = mesh.getWorldMatrix();
  78119. }
  78120. this._skeleton.computeAbsoluteTransforms();
  78121. var tmat = Bone._tmpMats[0];
  78122. tmat.copyFrom(this.getAbsoluteTransform());
  78123. if (mesh && wm) {
  78124. tmat.multiplyToRef(wm, tmat);
  78125. }
  78126. tmat.invert();
  78127. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78128. };
  78129. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78130. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78131. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78132. return Bone;
  78133. }(BABYLON.Node));
  78134. BABYLON.Bone = Bone;
  78135. })(BABYLON || (BABYLON = {}));
  78136. //# sourceMappingURL=babylon.bone.js.map
  78137. var BABYLON;
  78138. (function (BABYLON) {
  78139. /**
  78140. * Class used to apply inverse kinematics to bones
  78141. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78142. */
  78143. var BoneIKController = /** @class */ (function () {
  78144. /**
  78145. * Creates a new BoneIKController
  78146. * @param mesh defines the mesh to control
  78147. * @param bone defines the bone to control
  78148. * @param options defines options to set up the controller
  78149. */
  78150. function BoneIKController(mesh, bone, options) {
  78151. /**
  78152. * Gets or sets the target position
  78153. */
  78154. this.targetPosition = BABYLON.Vector3.Zero();
  78155. /**
  78156. * Gets or sets the pole target position
  78157. */
  78158. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78159. /**
  78160. * Gets or sets the pole target local offset
  78161. */
  78162. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78163. /**
  78164. * Gets or sets the pole angle
  78165. */
  78166. this.poleAngle = 0;
  78167. /**
  78168. * 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)
  78169. */
  78170. this.slerpAmount = 1;
  78171. this._bone1Quat = BABYLON.Quaternion.Identity();
  78172. this._bone1Mat = BABYLON.Matrix.Identity();
  78173. this._bone2Ang = Math.PI;
  78174. this._maxAngle = Math.PI;
  78175. this._rightHandedSystem = false;
  78176. this._bendAxis = BABYLON.Vector3.Right();
  78177. this._slerping = false;
  78178. this._adjustRoll = 0;
  78179. this._bone2 = bone;
  78180. this._bone1 = bone.getParent();
  78181. if (!this._bone1) {
  78182. return;
  78183. }
  78184. this.mesh = mesh;
  78185. var bonePos = bone.getPosition();
  78186. if (bone.getAbsoluteTransform().determinant() > 0) {
  78187. this._rightHandedSystem = true;
  78188. this._bendAxis.x = 0;
  78189. this._bendAxis.y = 0;
  78190. this._bendAxis.z = -1;
  78191. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78192. this._adjustRoll = Math.PI * .5;
  78193. this._bendAxis.z = 1;
  78194. }
  78195. }
  78196. if (this._bone1.length) {
  78197. var boneScale1 = this._bone1.getScale();
  78198. var boneScale2 = this._bone2.getScale();
  78199. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78200. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78201. }
  78202. else if (this._bone1.children[0]) {
  78203. mesh.computeWorldMatrix(true);
  78204. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78205. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78206. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78207. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78208. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78209. }
  78210. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78211. this.maxAngle = Math.PI;
  78212. if (options) {
  78213. if (options.targetMesh) {
  78214. this.targetMesh = options.targetMesh;
  78215. this.targetMesh.computeWorldMatrix(true);
  78216. }
  78217. if (options.poleTargetMesh) {
  78218. this.poleTargetMesh = options.poleTargetMesh;
  78219. this.poleTargetMesh.computeWorldMatrix(true);
  78220. }
  78221. else if (options.poleTargetBone) {
  78222. this.poleTargetBone = options.poleTargetBone;
  78223. }
  78224. else if (this._bone1.getParent()) {
  78225. this.poleTargetBone = this._bone1.getParent();
  78226. }
  78227. if (options.poleTargetLocalOffset) {
  78228. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78229. }
  78230. if (options.poleAngle) {
  78231. this.poleAngle = options.poleAngle;
  78232. }
  78233. if (options.bendAxis) {
  78234. this._bendAxis.copyFrom(options.bendAxis);
  78235. }
  78236. if (options.maxAngle) {
  78237. this.maxAngle = options.maxAngle;
  78238. }
  78239. if (options.slerpAmount) {
  78240. this.slerpAmount = options.slerpAmount;
  78241. }
  78242. }
  78243. }
  78244. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78245. /**
  78246. * Gets or sets maximum allowed angle
  78247. */
  78248. get: function () {
  78249. return this._maxAngle;
  78250. },
  78251. set: function (value) {
  78252. this._setMaxAngle(value);
  78253. },
  78254. enumerable: true,
  78255. configurable: true
  78256. });
  78257. BoneIKController.prototype._setMaxAngle = function (ang) {
  78258. if (ang < 0) {
  78259. ang = 0;
  78260. }
  78261. if (ang > Math.PI || ang == undefined) {
  78262. ang = Math.PI;
  78263. }
  78264. this._maxAngle = ang;
  78265. var a = this._bone1Length;
  78266. var b = this._bone2Length;
  78267. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78268. };
  78269. /**
  78270. * Force the controller to update the bones
  78271. */
  78272. BoneIKController.prototype.update = function () {
  78273. var bone1 = this._bone1;
  78274. if (!bone1) {
  78275. return;
  78276. }
  78277. var target = this.targetPosition;
  78278. var poleTarget = this.poleTargetPosition;
  78279. var mat1 = BoneIKController._tmpMats[0];
  78280. var mat2 = BoneIKController._tmpMats[1];
  78281. if (this.targetMesh) {
  78282. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78283. }
  78284. if (this.poleTargetBone) {
  78285. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78286. }
  78287. else if (this.poleTargetMesh) {
  78288. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78289. }
  78290. var bonePos = BoneIKController._tmpVecs[0];
  78291. var zaxis = BoneIKController._tmpVecs[1];
  78292. var xaxis = BoneIKController._tmpVecs[2];
  78293. var yaxis = BoneIKController._tmpVecs[3];
  78294. var upAxis = BoneIKController._tmpVecs[4];
  78295. var _tmpQuat = BoneIKController._tmpQuat;
  78296. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78297. poleTarget.subtractToRef(bonePos, upAxis);
  78298. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78299. upAxis.y = 1;
  78300. }
  78301. else {
  78302. upAxis.normalize();
  78303. }
  78304. target.subtractToRef(bonePos, yaxis);
  78305. yaxis.normalize();
  78306. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78307. zaxis.normalize();
  78308. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78309. xaxis.normalize();
  78310. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78311. var a = this._bone1Length;
  78312. var b = this._bone2Length;
  78313. var c = BABYLON.Vector3.Distance(bonePos, target);
  78314. if (this._maxReach > 0) {
  78315. c = Math.min(this._maxReach, c);
  78316. }
  78317. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78318. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78319. if (acosa > 1) {
  78320. acosa = 1;
  78321. }
  78322. if (acosb > 1) {
  78323. acosb = 1;
  78324. }
  78325. if (acosa < -1) {
  78326. acosa = -1;
  78327. }
  78328. if (acosb < -1) {
  78329. acosb = -1;
  78330. }
  78331. var angA = Math.acos(acosa);
  78332. var angB = Math.acos(acosb);
  78333. var angC = -angA - angB;
  78334. if (this._rightHandedSystem) {
  78335. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78336. mat2.multiplyToRef(mat1, mat1);
  78337. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78338. mat2.multiplyToRef(mat1, mat1);
  78339. }
  78340. else {
  78341. var _tmpVec = BoneIKController._tmpVecs[5];
  78342. _tmpVec.copyFrom(this._bendAxis);
  78343. _tmpVec.x *= -1;
  78344. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78345. mat2.multiplyToRef(mat1, mat1);
  78346. }
  78347. if (this.poleAngle) {
  78348. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78349. mat1.multiplyToRef(mat2, mat1);
  78350. }
  78351. if (this._bone1) {
  78352. if (this.slerpAmount < 1) {
  78353. if (!this._slerping) {
  78354. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78355. }
  78356. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78357. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78358. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78359. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78360. this._slerping = true;
  78361. }
  78362. else {
  78363. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78364. this._bone1Mat.copyFrom(mat1);
  78365. this._slerping = false;
  78366. }
  78367. }
  78368. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78369. this._bone2Ang = angC;
  78370. };
  78371. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78372. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78373. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78374. return BoneIKController;
  78375. }());
  78376. BABYLON.BoneIKController = BoneIKController;
  78377. })(BABYLON || (BABYLON = {}));
  78378. //# sourceMappingURL=babylon.boneIKController.js.map
  78379. var BABYLON;
  78380. (function (BABYLON) {
  78381. /**
  78382. * Class used to make a bone look toward a point in space
  78383. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78384. */
  78385. var BoneLookController = /** @class */ (function () {
  78386. /**
  78387. * Create a BoneLookController
  78388. * @param mesh the mesh that the bone belongs to
  78389. * @param bone the bone that will be looking to the target
  78390. * @param target the target Vector3 to look at
  78391. * @param settings optional settings:
  78392. * * maxYaw: the maximum angle the bone will yaw to
  78393. * * minYaw: the minimum angle the bone will yaw to
  78394. * * maxPitch: the maximum angle the bone will pitch to
  78395. * * minPitch: the minimum angle the bone will yaw to
  78396. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78397. * * upAxis: the up axis of the coordinate system
  78398. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78399. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78400. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78401. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78402. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78403. * * adjustRoll: used to make an adjustment to the roll of the bone
  78404. **/
  78405. function BoneLookController(mesh, bone, target, options) {
  78406. /**
  78407. * The up axis of the coordinate system that is used when the bone is rotated
  78408. */
  78409. this.upAxis = BABYLON.Vector3.Up();
  78410. /**
  78411. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78412. */
  78413. this.upAxisSpace = BABYLON.Space.LOCAL;
  78414. /**
  78415. * Used to make an adjustment to the yaw of the bone
  78416. */
  78417. this.adjustYaw = 0;
  78418. /**
  78419. * Used to make an adjustment to the pitch of the bone
  78420. */
  78421. this.adjustPitch = 0;
  78422. /**
  78423. * Used to make an adjustment to the roll of the bone
  78424. */
  78425. this.adjustRoll = 0;
  78426. /**
  78427. * 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)
  78428. */
  78429. this.slerpAmount = 1;
  78430. this._boneQuat = BABYLON.Quaternion.Identity();
  78431. this._slerping = false;
  78432. this._firstFrameSkipped = false;
  78433. this._fowardAxis = BABYLON.Vector3.Forward();
  78434. this.mesh = mesh;
  78435. this.bone = bone;
  78436. this.target = target;
  78437. if (options) {
  78438. if (options.adjustYaw) {
  78439. this.adjustYaw = options.adjustYaw;
  78440. }
  78441. if (options.adjustPitch) {
  78442. this.adjustPitch = options.adjustPitch;
  78443. }
  78444. if (options.adjustRoll) {
  78445. this.adjustRoll = options.adjustRoll;
  78446. }
  78447. if (options.maxYaw != null) {
  78448. this.maxYaw = options.maxYaw;
  78449. }
  78450. else {
  78451. this.maxYaw = Math.PI;
  78452. }
  78453. if (options.minYaw != null) {
  78454. this.minYaw = options.minYaw;
  78455. }
  78456. else {
  78457. this.minYaw = -Math.PI;
  78458. }
  78459. if (options.maxPitch != null) {
  78460. this.maxPitch = options.maxPitch;
  78461. }
  78462. else {
  78463. this.maxPitch = Math.PI;
  78464. }
  78465. if (options.minPitch != null) {
  78466. this.minPitch = options.minPitch;
  78467. }
  78468. else {
  78469. this.minPitch = -Math.PI;
  78470. }
  78471. if (options.slerpAmount != null) {
  78472. this.slerpAmount = options.slerpAmount;
  78473. }
  78474. if (options.upAxis != null) {
  78475. this.upAxis = options.upAxis;
  78476. }
  78477. if (options.upAxisSpace != null) {
  78478. this.upAxisSpace = options.upAxisSpace;
  78479. }
  78480. if (options.yawAxis != null || options.pitchAxis != null) {
  78481. var newYawAxis = BABYLON.Axis.Y;
  78482. var newPitchAxis = BABYLON.Axis.X;
  78483. if (options.yawAxis != null) {
  78484. newYawAxis = options.yawAxis.clone();
  78485. newYawAxis.normalize();
  78486. }
  78487. if (options.pitchAxis != null) {
  78488. newPitchAxis = options.pitchAxis.clone();
  78489. newPitchAxis.normalize();
  78490. }
  78491. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78492. this._transformYawPitch = BABYLON.Matrix.Identity();
  78493. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78494. this._transformYawPitchInv = this._transformYawPitch.clone();
  78495. this._transformYawPitch.invert();
  78496. }
  78497. }
  78498. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78499. this.upAxisSpace = BABYLON.Space.LOCAL;
  78500. }
  78501. }
  78502. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78503. /**
  78504. * Gets or sets the minimum yaw angle that the bone can look to
  78505. */
  78506. get: function () {
  78507. return this._minYaw;
  78508. },
  78509. set: function (value) {
  78510. this._minYaw = value;
  78511. this._minYawSin = Math.sin(value);
  78512. this._minYawCos = Math.cos(value);
  78513. if (this._maxYaw != null) {
  78514. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78515. this._yawRange = this._maxYaw - this._minYaw;
  78516. }
  78517. },
  78518. enumerable: true,
  78519. configurable: true
  78520. });
  78521. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78522. /**
  78523. * Gets or sets the maximum yaw angle that the bone can look to
  78524. */
  78525. get: function () {
  78526. return this._maxYaw;
  78527. },
  78528. set: function (value) {
  78529. this._maxYaw = value;
  78530. this._maxYawSin = Math.sin(value);
  78531. this._maxYawCos = Math.cos(value);
  78532. if (this._minYaw != null) {
  78533. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78534. this._yawRange = this._maxYaw - this._minYaw;
  78535. }
  78536. },
  78537. enumerable: true,
  78538. configurable: true
  78539. });
  78540. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78541. /**
  78542. * Gets or sets the minimum pitch angle that the bone can look to
  78543. */
  78544. get: function () {
  78545. return this._minPitch;
  78546. },
  78547. set: function (value) {
  78548. this._minPitch = value;
  78549. this._minPitchTan = Math.tan(value);
  78550. },
  78551. enumerable: true,
  78552. configurable: true
  78553. });
  78554. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78555. /**
  78556. * Gets or sets the maximum pitch angle that the bone can look to
  78557. */
  78558. get: function () {
  78559. return this._maxPitch;
  78560. },
  78561. set: function (value) {
  78562. this._maxPitch = value;
  78563. this._maxPitchTan = Math.tan(value);
  78564. },
  78565. enumerable: true,
  78566. configurable: true
  78567. });
  78568. /**
  78569. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78570. */
  78571. BoneLookController.prototype.update = function () {
  78572. //skip the first frame when slerping so that the mesh rotation is correct
  78573. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78574. this._firstFrameSkipped = true;
  78575. return;
  78576. }
  78577. var bone = this.bone;
  78578. var bonePos = BoneLookController._tmpVecs[0];
  78579. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78580. var target = this.target;
  78581. var _tmpMat1 = BoneLookController._tmpMats[0];
  78582. var _tmpMat2 = BoneLookController._tmpMats[1];
  78583. var mesh = this.mesh;
  78584. var parentBone = bone.getParent();
  78585. var upAxis = BoneLookController._tmpVecs[1];
  78586. upAxis.copyFrom(this.upAxis);
  78587. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78588. if (this._transformYawPitch) {
  78589. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78590. }
  78591. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78592. }
  78593. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78594. mesh.getDirectionToRef(upAxis, upAxis);
  78595. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78596. upAxis.normalize();
  78597. }
  78598. }
  78599. var checkYaw = false;
  78600. var checkPitch = false;
  78601. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78602. checkYaw = true;
  78603. }
  78604. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78605. checkPitch = true;
  78606. }
  78607. if (checkYaw || checkPitch) {
  78608. var spaceMat = BoneLookController._tmpMats[2];
  78609. var spaceMatInv = BoneLookController._tmpMats[3];
  78610. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78611. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78612. }
  78613. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78614. spaceMat.copyFrom(mesh.getWorldMatrix());
  78615. }
  78616. else {
  78617. var forwardAxis = BoneLookController._tmpVecs[2];
  78618. forwardAxis.copyFrom(this._fowardAxis);
  78619. if (this._transformYawPitch) {
  78620. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78621. }
  78622. if (parentBone) {
  78623. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78624. }
  78625. else {
  78626. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78627. }
  78628. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78629. rightAxis.normalize();
  78630. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78631. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78632. }
  78633. spaceMat.invertToRef(spaceMatInv);
  78634. var xzlen = null;
  78635. if (checkPitch) {
  78636. var localTarget = BoneLookController._tmpVecs[3];
  78637. target.subtractToRef(bonePos, localTarget);
  78638. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78639. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78640. var pitch = Math.atan2(localTarget.y, xzlen);
  78641. var newPitch = pitch;
  78642. if (pitch > this._maxPitch) {
  78643. localTarget.y = this._maxPitchTan * xzlen;
  78644. newPitch = this._maxPitch;
  78645. }
  78646. else if (pitch < this._minPitch) {
  78647. localTarget.y = this._minPitchTan * xzlen;
  78648. newPitch = this._minPitch;
  78649. }
  78650. if (pitch != newPitch) {
  78651. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78652. localTarget.addInPlace(bonePos);
  78653. target = localTarget;
  78654. }
  78655. }
  78656. if (checkYaw) {
  78657. var localTarget = BoneLookController._tmpVecs[4];
  78658. target.subtractToRef(bonePos, localTarget);
  78659. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78660. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78661. var newYaw = yaw;
  78662. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78663. if (xzlen == null) {
  78664. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78665. }
  78666. if (this._yawRange > Math.PI) {
  78667. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78668. localTarget.z = this._maxYawCos * xzlen;
  78669. localTarget.x = this._maxYawSin * xzlen;
  78670. newYaw = this._maxYaw;
  78671. }
  78672. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78673. localTarget.z = this._minYawCos * xzlen;
  78674. localTarget.x = this._minYawSin * xzlen;
  78675. newYaw = this._minYaw;
  78676. }
  78677. }
  78678. else {
  78679. if (yaw > this._maxYaw) {
  78680. localTarget.z = this._maxYawCos * xzlen;
  78681. localTarget.x = this._maxYawSin * xzlen;
  78682. newYaw = this._maxYaw;
  78683. }
  78684. else if (yaw < this._minYaw) {
  78685. localTarget.z = this._minYawCos * xzlen;
  78686. localTarget.x = this._minYawSin * xzlen;
  78687. newYaw = this._minYaw;
  78688. }
  78689. }
  78690. }
  78691. if (this._slerping && this._yawRange > Math.PI) {
  78692. //are we going to be crossing into the min/max region?
  78693. var boneFwd = BoneLookController._tmpVecs[8];
  78694. boneFwd.copyFrom(BABYLON.Axis.Z);
  78695. if (this._transformYawPitch) {
  78696. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78697. }
  78698. var boneRotMat = BoneLookController._tmpMats[4];
  78699. this._boneQuat.toRotationMatrix(boneRotMat);
  78700. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78701. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78702. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78703. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78704. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78705. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78706. if (angBtwTar > angBtwMidYaw) {
  78707. if (xzlen == null) {
  78708. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78709. }
  78710. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78711. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78712. if (angBtwMin < angBtwMax) {
  78713. newYaw = boneYaw + Math.PI * .75;
  78714. localTarget.z = Math.cos(newYaw) * xzlen;
  78715. localTarget.x = Math.sin(newYaw) * xzlen;
  78716. }
  78717. else {
  78718. newYaw = boneYaw - Math.PI * .75;
  78719. localTarget.z = Math.cos(newYaw) * xzlen;
  78720. localTarget.x = Math.sin(newYaw) * xzlen;
  78721. }
  78722. }
  78723. }
  78724. if (yaw != newYaw) {
  78725. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78726. localTarget.addInPlace(bonePos);
  78727. target = localTarget;
  78728. }
  78729. }
  78730. }
  78731. var zaxis = BoneLookController._tmpVecs[5];
  78732. var xaxis = BoneLookController._tmpVecs[6];
  78733. var yaxis = BoneLookController._tmpVecs[7];
  78734. var _tmpQuat = BoneLookController._tmpQuat;
  78735. target.subtractToRef(bonePos, zaxis);
  78736. zaxis.normalize();
  78737. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78738. xaxis.normalize();
  78739. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78740. yaxis.normalize();
  78741. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78742. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78743. return;
  78744. }
  78745. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78746. return;
  78747. }
  78748. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78749. return;
  78750. }
  78751. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78752. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78753. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78754. }
  78755. if (this.slerpAmount < 1) {
  78756. if (!this._slerping) {
  78757. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78758. }
  78759. if (this._transformYawPitch) {
  78760. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78761. }
  78762. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78763. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78764. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78765. this._slerping = true;
  78766. }
  78767. else {
  78768. if (this._transformYawPitch) {
  78769. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78770. }
  78771. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78772. this._slerping = false;
  78773. }
  78774. };
  78775. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78776. var angDiff = ang2 - ang1;
  78777. angDiff %= Math.PI * 2;
  78778. if (angDiff > Math.PI) {
  78779. angDiff -= Math.PI * 2;
  78780. }
  78781. else if (angDiff < -Math.PI) {
  78782. angDiff += Math.PI * 2;
  78783. }
  78784. return angDiff;
  78785. };
  78786. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78787. ang1 %= (2 * Math.PI);
  78788. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78789. ang2 %= (2 * Math.PI);
  78790. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78791. var ab = 0;
  78792. if (ang1 < ang2) {
  78793. ab = ang2 - ang1;
  78794. }
  78795. else {
  78796. ab = ang1 - ang2;
  78797. }
  78798. if (ab > Math.PI) {
  78799. ab = Math.PI * 2 - ab;
  78800. }
  78801. return ab;
  78802. };
  78803. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78804. ang %= (2 * Math.PI);
  78805. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78806. ang1 %= (2 * Math.PI);
  78807. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78808. ang2 %= (2 * Math.PI);
  78809. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78810. if (ang1 < ang2) {
  78811. if (ang > ang1 && ang < ang2) {
  78812. return true;
  78813. }
  78814. }
  78815. else {
  78816. if (ang > ang2 && ang < ang1) {
  78817. return true;
  78818. }
  78819. }
  78820. return false;
  78821. };
  78822. 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()];
  78823. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78824. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78825. return BoneLookController;
  78826. }());
  78827. BABYLON.BoneLookController = BoneLookController;
  78828. })(BABYLON || (BABYLON = {}));
  78829. //# sourceMappingURL=babylon.boneLookController.js.map
  78830. var BABYLON;
  78831. (function (BABYLON) {
  78832. /**
  78833. * Class used to handle skinning animations
  78834. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78835. */
  78836. var Skeleton = /** @class */ (function () {
  78837. /**
  78838. * Creates a new skeleton
  78839. * @param name defines the skeleton name
  78840. * @param id defines the skeleton Id
  78841. * @param scene defines the hosting scene
  78842. */
  78843. function Skeleton(
  78844. /** defines the skeleton name */
  78845. name,
  78846. /** defines the skeleton Id */
  78847. id, scene) {
  78848. this.name = name;
  78849. this.id = id;
  78850. /**
  78851. * Gets the list of child bones
  78852. */
  78853. this.bones = new Array();
  78854. /**
  78855. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78856. */
  78857. this.needInitialSkinMatrix = false;
  78858. this._isDirty = true;
  78859. this._meshesWithPoseMatrix = new Array();
  78860. this._identity = BABYLON.Matrix.Identity();
  78861. this._ranges = {};
  78862. this._lastAbsoluteTransformsUpdateId = -1;
  78863. /**
  78864. * Specifies if the skeleton should be serialized
  78865. */
  78866. this.doNotSerialize = false;
  78867. this._animationPropertiesOverride = null;
  78868. // Events
  78869. /**
  78870. * An observable triggered before computing the skeleton's matrices
  78871. */
  78872. this.onBeforeComputeObservable = new BABYLON.Observable();
  78873. this.bones = [];
  78874. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78875. scene.skeletons.push(this);
  78876. //make sure it will recalculate the matrix next time prepare is called.
  78877. this._isDirty = true;
  78878. }
  78879. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78880. /**
  78881. * Gets or sets the animation properties override
  78882. */
  78883. get: function () {
  78884. if (!this._animationPropertiesOverride) {
  78885. return this._scene.animationPropertiesOverride;
  78886. }
  78887. return this._animationPropertiesOverride;
  78888. },
  78889. set: function (value) {
  78890. this._animationPropertiesOverride = value;
  78891. },
  78892. enumerable: true,
  78893. configurable: true
  78894. });
  78895. // Members
  78896. /**
  78897. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78898. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78899. * @returns a Float32Array containing matrices data
  78900. */
  78901. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78902. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78903. return mesh._bonesTransformMatrices;
  78904. }
  78905. if (!this._transformMatrices) {
  78906. this.prepare();
  78907. }
  78908. return this._transformMatrices;
  78909. };
  78910. /**
  78911. * Gets the current hosting scene
  78912. * @returns a scene object
  78913. */
  78914. Skeleton.prototype.getScene = function () {
  78915. return this._scene;
  78916. };
  78917. // Methods
  78918. /**
  78919. * Gets a string representing the current skeleton data
  78920. * @param fullDetails defines a boolean indicating if we want a verbose version
  78921. * @returns a string representing the current skeleton data
  78922. */
  78923. Skeleton.prototype.toString = function (fullDetails) {
  78924. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78925. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78926. if (fullDetails) {
  78927. ret += ", Ranges: {";
  78928. var first = true;
  78929. for (var name_1 in this._ranges) {
  78930. if (first) {
  78931. ret += ", ";
  78932. first = false;
  78933. }
  78934. ret += name_1;
  78935. }
  78936. ret += "}";
  78937. }
  78938. return ret;
  78939. };
  78940. /**
  78941. * Get bone's index searching by name
  78942. * @param name defines bone's name to search for
  78943. * @return the indice of the bone. Returns -1 if not found
  78944. */
  78945. Skeleton.prototype.getBoneIndexByName = function (name) {
  78946. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78947. if (this.bones[boneIndex].name === name) {
  78948. return boneIndex;
  78949. }
  78950. }
  78951. return -1;
  78952. };
  78953. /**
  78954. * Creater a new animation range
  78955. * @param name defines the name of the range
  78956. * @param from defines the start key
  78957. * @param to defines the end key
  78958. */
  78959. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78960. // check name not already in use
  78961. if (!this._ranges[name]) {
  78962. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78963. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78964. if (this.bones[i].animations[0]) {
  78965. this.bones[i].animations[0].createRange(name, from, to);
  78966. }
  78967. }
  78968. }
  78969. };
  78970. /**
  78971. * Delete a specific animation range
  78972. * @param name defines the name of the range
  78973. * @param deleteFrames defines if frames must be removed as well
  78974. */
  78975. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  78976. if (deleteFrames === void 0) { deleteFrames = true; }
  78977. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78978. if (this.bones[i].animations[0]) {
  78979. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  78980. }
  78981. }
  78982. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  78983. };
  78984. /**
  78985. * Gets a specific animation range
  78986. * @param name defines the name of the range to look for
  78987. * @returns the requested animation range or null if not found
  78988. */
  78989. Skeleton.prototype.getAnimationRange = function (name) {
  78990. return this._ranges[name];
  78991. };
  78992. /**
  78993. * Gets the list of all animation ranges defined on this skeleton
  78994. * @returns an array
  78995. */
  78996. Skeleton.prototype.getAnimationRanges = function () {
  78997. var animationRanges = [];
  78998. var name;
  78999. var i = 0;
  79000. for (name in this._ranges) {
  79001. animationRanges[i] = this._ranges[name];
  79002. i++;
  79003. }
  79004. return animationRanges;
  79005. };
  79006. /**
  79007. * Copy animation range from a source skeleton.
  79008. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79009. * @param source defines the source skeleton
  79010. * @param name defines the name of the range to copy
  79011. * @param rescaleAsRequired defines if rescaling must be applied if required
  79012. * @returns true if operation was successful
  79013. */
  79014. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79015. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79016. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79017. return false;
  79018. }
  79019. var ret = true;
  79020. var frameOffset = this._getHighestAnimationFrame() + 1;
  79021. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79022. var boneDict = {};
  79023. var sourceBones = source.bones;
  79024. var nBones;
  79025. var i;
  79026. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79027. boneDict[sourceBones[i].name] = sourceBones[i];
  79028. }
  79029. if (this.bones.length !== sourceBones.length) {
  79030. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79031. ret = false;
  79032. }
  79033. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79034. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79035. var boneName = this.bones[i].name;
  79036. var sourceBone = boneDict[boneName];
  79037. if (sourceBone) {
  79038. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79039. }
  79040. else {
  79041. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79042. ret = false;
  79043. }
  79044. }
  79045. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79046. var range = source.getAnimationRange(name);
  79047. if (range) {
  79048. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79049. }
  79050. return ret;
  79051. };
  79052. /**
  79053. * Forces the skeleton to go to rest pose
  79054. */
  79055. Skeleton.prototype.returnToRest = function () {
  79056. for (var index = 0; index < this.bones.length; index++) {
  79057. this.bones[index].returnToRest();
  79058. }
  79059. };
  79060. Skeleton.prototype._getHighestAnimationFrame = function () {
  79061. var ret = 0;
  79062. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79063. if (this.bones[i].animations[0]) {
  79064. var highest = this.bones[i].animations[0].getHighestFrame();
  79065. if (ret < highest) {
  79066. ret = highest;
  79067. }
  79068. }
  79069. }
  79070. return ret;
  79071. };
  79072. /**
  79073. * Begin a specific animation range
  79074. * @param name defines the name of the range to start
  79075. * @param loop defines if looping must be turned on (false by default)
  79076. * @param speedRatio defines the speed ratio to apply (1 by default)
  79077. * @param onAnimationEnd defines a callback which will be called when animation will end
  79078. * @returns a new animatable
  79079. */
  79080. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79081. var range = this.getAnimationRange(name);
  79082. if (!range) {
  79083. return null;
  79084. }
  79085. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79086. };
  79087. /** @hidden */
  79088. Skeleton.prototype._markAsDirty = function () {
  79089. this._isDirty = true;
  79090. };
  79091. /** @hidden */
  79092. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79093. this._meshesWithPoseMatrix.push(mesh);
  79094. };
  79095. /** @hidden */
  79096. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79097. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79098. if (index > -1) {
  79099. this._meshesWithPoseMatrix.splice(index, 1);
  79100. }
  79101. };
  79102. /** @hidden */
  79103. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79104. this.onBeforeComputeObservable.notifyObservers(this);
  79105. for (var index = 0; index < this.bones.length; index++) {
  79106. var bone = this.bones[index];
  79107. var parentBone = bone.getParent();
  79108. if (parentBone) {
  79109. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79110. }
  79111. else {
  79112. if (initialSkinMatrix) {
  79113. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79114. }
  79115. else {
  79116. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79117. }
  79118. }
  79119. if (bone._index !== -1) {
  79120. var mappedIndex = bone._index === null ? index : bone._index;
  79121. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79122. }
  79123. }
  79124. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79125. };
  79126. /**
  79127. * Build all resources required to render a skeleton
  79128. */
  79129. Skeleton.prototype.prepare = function () {
  79130. if (!this._isDirty) {
  79131. return;
  79132. }
  79133. if (this.needInitialSkinMatrix) {
  79134. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79135. var mesh = this._meshesWithPoseMatrix[index];
  79136. var poseMatrix = mesh.getPoseMatrix();
  79137. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79138. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79139. }
  79140. if (this._synchronizedWithMesh !== mesh) {
  79141. this._synchronizedWithMesh = mesh;
  79142. // Prepare bones
  79143. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79144. var bone = this.bones[boneIndex];
  79145. if (!bone.getParent()) {
  79146. var matrix = bone.getBaseMatrix();
  79147. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79148. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79149. }
  79150. }
  79151. }
  79152. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79153. }
  79154. }
  79155. else {
  79156. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79157. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79158. }
  79159. this._computeTransformMatrices(this._transformMatrices, null);
  79160. }
  79161. this._isDirty = false;
  79162. this._scene._activeBones.addCount(this.bones.length, false);
  79163. };
  79164. /**
  79165. * Gets the list of animatables currently running for this skeleton
  79166. * @returns an array of animatables
  79167. */
  79168. Skeleton.prototype.getAnimatables = function () {
  79169. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79170. this._animatables = [];
  79171. for (var index = 0; index < this.bones.length; index++) {
  79172. this._animatables.push(this.bones[index]);
  79173. }
  79174. }
  79175. return this._animatables;
  79176. };
  79177. /**
  79178. * Clone the current skeleton
  79179. * @param name defines the name of the new skeleton
  79180. * @param id defines the id of the enw skeleton
  79181. * @returns the new skeleton
  79182. */
  79183. Skeleton.prototype.clone = function (name, id) {
  79184. var result = new Skeleton(name, id || name, this._scene);
  79185. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79186. for (var index = 0; index < this.bones.length; index++) {
  79187. var source = this.bones[index];
  79188. var parentBone = null;
  79189. var parent_1 = source.getParent();
  79190. if (parent_1) {
  79191. var parentIndex = this.bones.indexOf(parent_1);
  79192. parentBone = result.bones[parentIndex];
  79193. }
  79194. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79195. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79196. }
  79197. if (this._ranges) {
  79198. result._ranges = {};
  79199. for (var rangeName in this._ranges) {
  79200. var range = this._ranges[rangeName];
  79201. if (range) {
  79202. result._ranges[rangeName] = range.clone();
  79203. }
  79204. }
  79205. }
  79206. this._isDirty = true;
  79207. return result;
  79208. };
  79209. /**
  79210. * Enable animation blending for this skeleton
  79211. * @param blendingSpeed defines the blending speed to apply
  79212. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79213. */
  79214. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79215. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79216. this.bones.forEach(function (bone) {
  79217. bone.animations.forEach(function (animation) {
  79218. animation.enableBlending = true;
  79219. animation.blendingSpeed = blendingSpeed;
  79220. });
  79221. });
  79222. };
  79223. /**
  79224. * Releases all resources associated with the current skeleton
  79225. */
  79226. Skeleton.prototype.dispose = function () {
  79227. this._meshesWithPoseMatrix = [];
  79228. // Animations
  79229. this.getScene().stopAnimation(this);
  79230. // Remove from scene
  79231. this.getScene().removeSkeleton(this);
  79232. };
  79233. /**
  79234. * Serialize the skeleton in a JSON object
  79235. * @returns a JSON object
  79236. */
  79237. Skeleton.prototype.serialize = function () {
  79238. var serializationObject = {};
  79239. serializationObject.name = this.name;
  79240. serializationObject.id = this.id;
  79241. if (this.dimensionsAtRest) {
  79242. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79243. }
  79244. serializationObject.bones = [];
  79245. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79246. for (var index = 0; index < this.bones.length; index++) {
  79247. var bone = this.bones[index];
  79248. var parent_2 = bone.getParent();
  79249. var serializedBone = {
  79250. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79251. name: bone.name,
  79252. matrix: bone.getBaseMatrix().toArray(),
  79253. rest: bone.getRestPose().toArray()
  79254. };
  79255. serializationObject.bones.push(serializedBone);
  79256. if (bone.length) {
  79257. serializedBone.length = bone.length;
  79258. }
  79259. if (bone.animations && bone.animations.length > 0) {
  79260. serializedBone.animation = bone.animations[0].serialize();
  79261. }
  79262. serializationObject.ranges = [];
  79263. for (var name in this._ranges) {
  79264. var source = this._ranges[name];
  79265. if (!source) {
  79266. continue;
  79267. }
  79268. var range = {};
  79269. range.name = name;
  79270. range.from = source.from;
  79271. range.to = source.to;
  79272. serializationObject.ranges.push(range);
  79273. }
  79274. }
  79275. return serializationObject;
  79276. };
  79277. /**
  79278. * Creates a new skeleton from serialized data
  79279. * @param parsedSkeleton defines the serialized data
  79280. * @param scene defines the hosting scene
  79281. * @returns a new skeleton
  79282. */
  79283. Skeleton.Parse = function (parsedSkeleton, scene) {
  79284. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79285. if (parsedSkeleton.dimensionsAtRest) {
  79286. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79287. }
  79288. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79289. var index;
  79290. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79291. var parsedBone = parsedSkeleton.bones[index];
  79292. var parentBone = null;
  79293. if (parsedBone.parentBoneIndex > -1) {
  79294. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79295. }
  79296. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79297. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79298. if (parsedBone.length) {
  79299. bone.length = parsedBone.length;
  79300. }
  79301. if (parsedBone.animation) {
  79302. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79303. }
  79304. }
  79305. // placed after bones, so createAnimationRange can cascade down
  79306. if (parsedSkeleton.ranges) {
  79307. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79308. var data = parsedSkeleton.ranges[index];
  79309. skeleton.createAnimationRange(data.name, data.from, data.to);
  79310. }
  79311. }
  79312. return skeleton;
  79313. };
  79314. /**
  79315. * Compute all node absolute transforms
  79316. * @param forceUpdate defines if computation must be done even if cache is up to date
  79317. */
  79318. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79319. if (forceUpdate === void 0) { forceUpdate = false; }
  79320. var renderId = this._scene.getRenderId();
  79321. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79322. this.bones[0].computeAbsoluteTransforms();
  79323. this._lastAbsoluteTransformsUpdateId = renderId;
  79324. }
  79325. };
  79326. /**
  79327. * Gets the root pose matrix
  79328. * @returns a matrix
  79329. */
  79330. Skeleton.prototype.getPoseMatrix = function () {
  79331. var poseMatrix = null;
  79332. if (this._meshesWithPoseMatrix.length > 0) {
  79333. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79334. }
  79335. return poseMatrix;
  79336. };
  79337. /**
  79338. * Sorts bones per internal index
  79339. */
  79340. Skeleton.prototype.sortBones = function () {
  79341. var bones = new Array();
  79342. var visited = new Array(this.bones.length);
  79343. for (var index = 0; index < this.bones.length; index++) {
  79344. this._sortBones(index, bones, visited);
  79345. }
  79346. this.bones = bones;
  79347. };
  79348. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79349. if (visited[index]) {
  79350. return;
  79351. }
  79352. visited[index] = true;
  79353. var bone = this.bones[index];
  79354. if (bone._index === undefined) {
  79355. bone._index = index;
  79356. }
  79357. var parentBone = bone.getParent();
  79358. if (parentBone) {
  79359. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79360. }
  79361. bones.push(bone);
  79362. };
  79363. return Skeleton;
  79364. }());
  79365. BABYLON.Skeleton = Skeleton;
  79366. })(BABYLON || (BABYLON = {}));
  79367. //# sourceMappingURL=babylon.skeleton.js.map
  79368. var BABYLON;
  79369. (function (BABYLON) {
  79370. var SphericalPolynomial = /** @class */ (function () {
  79371. function SphericalPolynomial() {
  79372. this.x = BABYLON.Vector3.Zero();
  79373. this.y = BABYLON.Vector3.Zero();
  79374. this.z = BABYLON.Vector3.Zero();
  79375. this.xx = BABYLON.Vector3.Zero();
  79376. this.yy = BABYLON.Vector3.Zero();
  79377. this.zz = BABYLON.Vector3.Zero();
  79378. this.xy = BABYLON.Vector3.Zero();
  79379. this.yz = BABYLON.Vector3.Zero();
  79380. this.zx = BABYLON.Vector3.Zero();
  79381. }
  79382. SphericalPolynomial.prototype.addAmbient = function (color) {
  79383. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79384. this.xx = this.xx.add(colorVector);
  79385. this.yy = this.yy.add(colorVector);
  79386. this.zz = this.zz.add(colorVector);
  79387. };
  79388. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79389. var result = new SphericalPolynomial();
  79390. result.x = harmonics.L11.scale(1.02333);
  79391. result.y = harmonics.L1_1.scale(1.02333);
  79392. result.z = harmonics.L10.scale(1.02333);
  79393. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79394. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79395. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79396. result.yz = harmonics.L2_1.scale(0.858086);
  79397. result.zx = harmonics.L21.scale(0.858086);
  79398. result.xy = harmonics.L2_2.scale(0.858086);
  79399. result.scale(1.0 / Math.PI);
  79400. return result;
  79401. };
  79402. SphericalPolynomial.prototype.scale = function (scale) {
  79403. this.x = this.x.scale(scale);
  79404. this.y = this.y.scale(scale);
  79405. this.z = this.z.scale(scale);
  79406. this.xx = this.xx.scale(scale);
  79407. this.yy = this.yy.scale(scale);
  79408. this.zz = this.zz.scale(scale);
  79409. this.yz = this.yz.scale(scale);
  79410. this.zx = this.zx.scale(scale);
  79411. this.xy = this.xy.scale(scale);
  79412. };
  79413. return SphericalPolynomial;
  79414. }());
  79415. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79416. var SphericalHarmonics = /** @class */ (function () {
  79417. function SphericalHarmonics() {
  79418. this.L00 = BABYLON.Vector3.Zero();
  79419. this.L1_1 = BABYLON.Vector3.Zero();
  79420. this.L10 = BABYLON.Vector3.Zero();
  79421. this.L11 = BABYLON.Vector3.Zero();
  79422. this.L2_2 = BABYLON.Vector3.Zero();
  79423. this.L2_1 = BABYLON.Vector3.Zero();
  79424. this.L20 = BABYLON.Vector3.Zero();
  79425. this.L21 = BABYLON.Vector3.Zero();
  79426. this.L22 = BABYLON.Vector3.Zero();
  79427. }
  79428. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79429. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79430. var c = colorVector.scale(deltaSolidAngle);
  79431. this.L00 = this.L00.add(c.scale(0.282095));
  79432. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79433. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79434. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79435. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79436. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79437. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79438. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79439. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79440. };
  79441. SphericalHarmonics.prototype.scale = function (scale) {
  79442. this.L00 = this.L00.scale(scale);
  79443. this.L1_1 = this.L1_1.scale(scale);
  79444. this.L10 = this.L10.scale(scale);
  79445. this.L11 = this.L11.scale(scale);
  79446. this.L2_2 = this.L2_2.scale(scale);
  79447. this.L2_1 = this.L2_1.scale(scale);
  79448. this.L20 = this.L20.scale(scale);
  79449. this.L21 = this.L21.scale(scale);
  79450. this.L22 = this.L22.scale(scale);
  79451. };
  79452. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79453. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79454. //
  79455. // E_lm = A_l * L_lm
  79456. //
  79457. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79458. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79459. // the scaling factors are given in equation 9.
  79460. // Constant (Band 0)
  79461. this.L00 = this.L00.scale(3.141593);
  79462. // Linear (Band 1)
  79463. this.L1_1 = this.L1_1.scale(2.094395);
  79464. this.L10 = this.L10.scale(2.094395);
  79465. this.L11 = this.L11.scale(2.094395);
  79466. // Quadratic (Band 2)
  79467. this.L2_2 = this.L2_2.scale(0.785398);
  79468. this.L2_1 = this.L2_1.scale(0.785398);
  79469. this.L20 = this.L20.scale(0.785398);
  79470. this.L21 = this.L21.scale(0.785398);
  79471. this.L22 = this.L22.scale(0.785398);
  79472. };
  79473. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79474. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79475. // L = (1/pi) * E * rho
  79476. //
  79477. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79478. this.scale(1.0 / Math.PI);
  79479. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79480. // (The pixel shader must apply albedo after texture fetches, etc).
  79481. };
  79482. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79483. var result = new SphericalHarmonics();
  79484. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79485. result.L1_1 = polynomial.y.scale(0.977204);
  79486. result.L10 = polynomial.z.scale(0.977204);
  79487. result.L11 = polynomial.x.scale(0.977204);
  79488. result.L2_2 = polynomial.xy.scale(1.16538);
  79489. result.L2_1 = polynomial.yz.scale(1.16538);
  79490. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79491. result.L21 = polynomial.zx.scale(1.16538);
  79492. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79493. result.scale(Math.PI);
  79494. return result;
  79495. };
  79496. return SphericalHarmonics;
  79497. }());
  79498. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79499. })(BABYLON || (BABYLON = {}));
  79500. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79501. var BABYLON;
  79502. (function (BABYLON) {
  79503. var FileFaceOrientation = /** @class */ (function () {
  79504. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79505. this.name = name;
  79506. this.worldAxisForNormal = worldAxisForNormal;
  79507. this.worldAxisForFileX = worldAxisForFileX;
  79508. this.worldAxisForFileY = worldAxisForFileY;
  79509. }
  79510. return FileFaceOrientation;
  79511. }());
  79512. ;
  79513. /**
  79514. * Helper class dealing with the extraction of spherical polynomial dataArray
  79515. * from a cube map.
  79516. */
  79517. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79518. function CubeMapToSphericalPolynomialTools() {
  79519. }
  79520. /**
  79521. * Converts a texture to the according Spherical Polynomial data.
  79522. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79523. *
  79524. * @param texture The texture to extract the information from.
  79525. * @return The Spherical Polynomial data.
  79526. */
  79527. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79528. if (!texture.isCube) {
  79529. // Only supports cube Textures currently.
  79530. return null;
  79531. }
  79532. var size = texture.getSize().width;
  79533. var right = texture.readPixels(0);
  79534. var left = texture.readPixels(1);
  79535. var up;
  79536. var down;
  79537. if (texture.isRenderTarget) {
  79538. up = texture.readPixels(3);
  79539. down = texture.readPixels(2);
  79540. }
  79541. else {
  79542. up = texture.readPixels(2);
  79543. down = texture.readPixels(3);
  79544. }
  79545. var front = texture.readPixels(4);
  79546. var back = texture.readPixels(5);
  79547. var gammaSpace = texture.gammaSpace;
  79548. // Always read as RGBA.
  79549. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79550. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79551. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79552. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79553. }
  79554. var cubeInfo = {
  79555. size: size,
  79556. right: right,
  79557. left: left,
  79558. up: up,
  79559. down: down,
  79560. front: front,
  79561. back: back,
  79562. format: format,
  79563. type: type,
  79564. gammaSpace: gammaSpace,
  79565. };
  79566. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79567. };
  79568. /**
  79569. * Converts a cubemap to the according Spherical Polynomial data.
  79570. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79571. *
  79572. * @param cubeInfo The Cube map to extract the information from.
  79573. * @return The Spherical Polynomial data.
  79574. */
  79575. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79576. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79577. var totalSolidAngle = 0.0;
  79578. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79579. var du = 2.0 / cubeInfo.size;
  79580. var dv = du;
  79581. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79582. var minUV = du * 0.5 - 1.0;
  79583. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79584. var fileFace = this.FileFaces[faceIndex];
  79585. var dataArray = cubeInfo[fileFace.name];
  79586. var v = minUV;
  79587. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79588. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79589. // Because SP is still linear, so summation is fine in that basis.
  79590. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79591. for (var y = 0; y < cubeInfo.size; y++) {
  79592. var u = minUV;
  79593. for (var x = 0; x < cubeInfo.size; x++) {
  79594. // World direction (not normalised)
  79595. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79596. worldDirection.normalize();
  79597. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79598. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79599. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79600. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79601. // Handle Integer types.
  79602. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79603. r /= 255;
  79604. g /= 255;
  79605. b /= 255;
  79606. }
  79607. // Handle Gamma space textures.
  79608. if (cubeInfo.gammaSpace) {
  79609. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79610. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79611. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79612. }
  79613. var color = new BABYLON.Color3(r, g, b);
  79614. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79615. totalSolidAngle += deltaSolidAngle;
  79616. u += du;
  79617. }
  79618. v += dv;
  79619. }
  79620. }
  79621. // Solid angle for entire sphere is 4*pi
  79622. var sphereSolidAngle = 4.0 * Math.PI;
  79623. // Adjust the solid angle to allow for how many faces we processed.
  79624. var facesProcessed = 6.0;
  79625. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79626. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79627. // This is needed because the numerical integration over the cube uses a
  79628. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79629. // and also to compensate for accumulative error due to float precision in the summation.
  79630. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79631. sphericalHarmonics.scale(correctionFactor);
  79632. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79633. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79634. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79635. };
  79636. CubeMapToSphericalPolynomialTools.FileFaces = [
  79637. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79638. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79639. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79640. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79641. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79642. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79643. ];
  79644. return CubeMapToSphericalPolynomialTools;
  79645. }());
  79646. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79647. })(BABYLON || (BABYLON = {}));
  79648. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79649. var BABYLON;
  79650. (function (BABYLON) {
  79651. /**
  79652. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79653. */
  79654. var PanoramaToCubeMapTools = /** @class */ (function () {
  79655. function PanoramaToCubeMapTools() {
  79656. }
  79657. /**
  79658. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79659. *
  79660. * @param float32Array The source data.
  79661. * @param inputWidth The width of the input panorama.
  79662. * @param inputhHeight The height of the input panorama.
  79663. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79664. * @return The cubemap data
  79665. */
  79666. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79667. if (!float32Array) {
  79668. throw "ConvertPanoramaToCubemap: input cannot be null";
  79669. }
  79670. if (float32Array.length != inputWidth * inputHeight * 3) {
  79671. throw "ConvertPanoramaToCubemap: input size is wrong";
  79672. }
  79673. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79674. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79675. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79676. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79677. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79678. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79679. return {
  79680. front: textureFront,
  79681. back: textureBack,
  79682. left: textureLeft,
  79683. right: textureRight,
  79684. up: textureUp,
  79685. down: textureDown,
  79686. size: size,
  79687. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79688. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79689. gammaSpace: false,
  79690. };
  79691. };
  79692. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79693. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79694. var textureArray = new Float32Array(buffer);
  79695. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79696. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79697. var dy = 1 / texSize;
  79698. var fy = 0;
  79699. for (var y = 0; y < texSize; y++) {
  79700. var xv1 = faceData[0];
  79701. var xv2 = faceData[2];
  79702. for (var x = 0; x < texSize; x++) {
  79703. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79704. v.normalize();
  79705. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79706. // 3 channels per pixels
  79707. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79708. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79709. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79710. xv1 = xv1.add(rotDX1);
  79711. xv2 = xv2.add(rotDX2);
  79712. }
  79713. fy += dy;
  79714. }
  79715. return textureArray;
  79716. };
  79717. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79718. var theta = Math.atan2(vDir.z, vDir.x);
  79719. var phi = Math.acos(vDir.y);
  79720. while (theta < -Math.PI)
  79721. theta += 2 * Math.PI;
  79722. while (theta > Math.PI)
  79723. theta -= 2 * Math.PI;
  79724. var dx = theta / Math.PI;
  79725. var dy = phi / Math.PI;
  79726. // recenter.
  79727. dx = dx * 0.5 + 0.5;
  79728. var px = Math.round(dx * inputWidth);
  79729. if (px < 0)
  79730. px = 0;
  79731. else if (px >= inputWidth)
  79732. px = inputWidth - 1;
  79733. var py = Math.round(dy * inputHeight);
  79734. if (py < 0)
  79735. py = 0;
  79736. else if (py >= inputHeight)
  79737. py = inputHeight - 1;
  79738. var inputY = (inputHeight - py - 1);
  79739. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79740. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79741. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79742. return {
  79743. r: r,
  79744. g: g,
  79745. b: b
  79746. };
  79747. };
  79748. PanoramaToCubeMapTools.FACE_FRONT = [
  79749. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79750. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79751. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79752. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79753. ];
  79754. PanoramaToCubeMapTools.FACE_BACK = [
  79755. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79756. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79757. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79758. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79759. ];
  79760. PanoramaToCubeMapTools.FACE_RIGHT = [
  79761. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79762. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79763. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79764. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79765. ];
  79766. PanoramaToCubeMapTools.FACE_LEFT = [
  79767. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79768. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79769. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79770. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79771. ];
  79772. PanoramaToCubeMapTools.FACE_DOWN = [
  79773. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79774. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79775. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79776. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79777. ];
  79778. PanoramaToCubeMapTools.FACE_UP = [
  79779. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79780. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79781. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79782. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79783. ];
  79784. return PanoramaToCubeMapTools;
  79785. }());
  79786. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79787. })(BABYLON || (BABYLON = {}));
  79788. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79789. var BABYLON;
  79790. (function (BABYLON) {
  79791. ;
  79792. /**
  79793. * This groups tools to convert HDR texture to native colors array.
  79794. */
  79795. var HDRTools = /** @class */ (function () {
  79796. function HDRTools() {
  79797. }
  79798. HDRTools.Ldexp = function (mantissa, exponent) {
  79799. if (exponent > 1023) {
  79800. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79801. }
  79802. if (exponent < -1074) {
  79803. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79804. }
  79805. return mantissa * Math.pow(2, exponent);
  79806. };
  79807. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79808. if (exponent > 0) { /*nonzero pixel*/
  79809. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79810. float32array[index + 0] = red * exponent;
  79811. float32array[index + 1] = green * exponent;
  79812. float32array[index + 2] = blue * exponent;
  79813. }
  79814. else {
  79815. float32array[index + 0] = 0;
  79816. float32array[index + 1] = 0;
  79817. float32array[index + 2] = 0;
  79818. }
  79819. };
  79820. HDRTools.readStringLine = function (uint8array, startIndex) {
  79821. var line = "";
  79822. var character = "";
  79823. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79824. character = String.fromCharCode(uint8array[i]);
  79825. if (character == "\n") {
  79826. break;
  79827. }
  79828. line += character;
  79829. }
  79830. return line;
  79831. };
  79832. /**
  79833. * Reads header information from an RGBE texture stored in a native array.
  79834. * More information on this format are available here:
  79835. * https://en.wikipedia.org/wiki/RGBE_image_format
  79836. *
  79837. * @param uint8array The binary file stored in native array.
  79838. * @return The header information.
  79839. */
  79840. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79841. var height = 0;
  79842. var width = 0;
  79843. var line = this.readStringLine(uint8array, 0);
  79844. if (line[0] != '#' || line[1] != '?') {
  79845. throw "Bad HDR Format.";
  79846. }
  79847. var endOfHeader = false;
  79848. var findFormat = false;
  79849. var lineIndex = 0;
  79850. do {
  79851. lineIndex += (line.length + 1);
  79852. line = this.readStringLine(uint8array, lineIndex);
  79853. if (line == "FORMAT=32-bit_rle_rgbe") {
  79854. findFormat = true;
  79855. }
  79856. else if (line.length == 0) {
  79857. endOfHeader = true;
  79858. }
  79859. } while (!endOfHeader);
  79860. if (!findFormat) {
  79861. throw "HDR Bad header format, unsupported FORMAT";
  79862. }
  79863. lineIndex += (line.length + 1);
  79864. line = this.readStringLine(uint8array, lineIndex);
  79865. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79866. var match = sizeRegexp.exec(line);
  79867. // TODO. Support +Y and -X if needed.
  79868. if (!match || match.length < 3) {
  79869. throw "HDR Bad header format, no size";
  79870. }
  79871. width = parseInt(match[2]);
  79872. height = parseInt(match[1]);
  79873. if (width < 8 || width > 0x7fff) {
  79874. throw "HDR Bad header format, unsupported size";
  79875. }
  79876. lineIndex += (line.length + 1);
  79877. return {
  79878. height: height,
  79879. width: width,
  79880. dataPosition: lineIndex
  79881. };
  79882. };
  79883. /**
  79884. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79885. * This RGBE texture needs to store the information as a panorama.
  79886. *
  79887. * More information on this format are available here:
  79888. * https://en.wikipedia.org/wiki/RGBE_image_format
  79889. *
  79890. * @param buffer The binary file stored in an array buffer.
  79891. * @param size The expected size of the extracted cubemap.
  79892. * @return The Cube Map information.
  79893. */
  79894. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79895. var uint8array = new Uint8Array(buffer);
  79896. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79897. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79898. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79899. return cubeMapData;
  79900. };
  79901. /**
  79902. * Returns the pixels data extracted from an RGBE texture.
  79903. * This pixels will be stored left to right up to down in the R G B order in one array.
  79904. *
  79905. * More information on this format are available here:
  79906. * https://en.wikipedia.org/wiki/RGBE_image_format
  79907. *
  79908. * @param uint8array The binary file stored in an array buffer.
  79909. * @param hdrInfo The header information of the file.
  79910. * @return The pixels data in RGB right to left up to down order.
  79911. */
  79912. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79913. // Keep for multi format supports.
  79914. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79915. };
  79916. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79917. var num_scanlines = hdrInfo.height;
  79918. var scanline_width = hdrInfo.width;
  79919. var a, b, c, d, count;
  79920. var dataIndex = hdrInfo.dataPosition;
  79921. var index = 0, endIndex = 0, i = 0;
  79922. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79923. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79924. // 3 channels of 4 bytes per pixel in float.
  79925. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79926. var resultArray = new Float32Array(resultBuffer);
  79927. // read in each successive scanline
  79928. while (num_scanlines > 0) {
  79929. a = uint8array[dataIndex++];
  79930. b = uint8array[dataIndex++];
  79931. c = uint8array[dataIndex++];
  79932. d = uint8array[dataIndex++];
  79933. if (a != 2 || b != 2 || (c & 0x80)) {
  79934. // this file is not run length encoded
  79935. throw "HDR Bad header format, not RLE";
  79936. }
  79937. if (((c << 8) | d) != scanline_width) {
  79938. throw "HDR Bad header format, wrong scan line width";
  79939. }
  79940. index = 0;
  79941. // read each of the four channels for the scanline into the buffer
  79942. for (i = 0; i < 4; i++) {
  79943. endIndex = (i + 1) * scanline_width;
  79944. while (index < endIndex) {
  79945. a = uint8array[dataIndex++];
  79946. b = uint8array[dataIndex++];
  79947. if (a > 128) {
  79948. // a run of the same value
  79949. count = a - 128;
  79950. if ((count == 0) || (count > endIndex - index)) {
  79951. throw "HDR Bad Format, bad scanline data (run)";
  79952. }
  79953. while (count-- > 0) {
  79954. scanLineArray[index++] = b;
  79955. }
  79956. }
  79957. else {
  79958. // a non-run
  79959. count = a;
  79960. if ((count == 0) || (count > endIndex - index)) {
  79961. throw "HDR Bad Format, bad scanline data (non-run)";
  79962. }
  79963. scanLineArray[index++] = b;
  79964. if (--count > 0) {
  79965. for (var j = 0; j < count; j++) {
  79966. scanLineArray[index++] = uint8array[dataIndex++];
  79967. }
  79968. }
  79969. }
  79970. }
  79971. }
  79972. // now convert data from buffer into floats
  79973. for (i = 0; i < scanline_width; i++) {
  79974. a = scanLineArray[i];
  79975. b = scanLineArray[i + scanline_width];
  79976. c = scanLineArray[i + 2 * scanline_width];
  79977. d = scanLineArray[i + 3 * scanline_width];
  79978. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  79979. }
  79980. num_scanlines--;
  79981. }
  79982. return resultArray;
  79983. };
  79984. return HDRTools;
  79985. }());
  79986. BABYLON.HDRTools = HDRTools;
  79987. })(BABYLON || (BABYLON = {}));
  79988. //# sourceMappingURL=babylon.hdr.js.map
  79989. var BABYLON;
  79990. (function (BABYLON) {
  79991. /**
  79992. * This represents a texture coming from an HDR input.
  79993. *
  79994. * The only supported format is currently panorama picture stored in RGBE format.
  79995. * Example of such files can be found on HDRLib: http://hdrlib.com/
  79996. */
  79997. var HDRCubeTexture = /** @class */ (function (_super) {
  79998. __extends(HDRCubeTexture, _super);
  79999. /**
  80000. * Instantiates an HDRTexture from the following parameters.
  80001. *
  80002. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80003. * @param scene The scene the texture will be used in
  80004. * @param size The cubemap 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.
  80005. * @param noMipmap Forces to not generate the mipmap if true
  80006. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80007. * @param useInGammaSpace 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)
  80008. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  80009. */
  80010. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  80011. if (noMipmap === void 0) { noMipmap = false; }
  80012. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80013. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80014. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80015. if (onLoad === void 0) { onLoad = null; }
  80016. if (onError === void 0) { onError = null; }
  80017. var _this = _super.call(this, scene) || this;
  80018. _this._useInGammaSpace = false;
  80019. _this._generateHarmonics = true;
  80020. _this._isBABYLONPreprocessed = false;
  80021. _this._onLoad = null;
  80022. _this._onError = null;
  80023. /**
  80024. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80025. */
  80026. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80027. /**
  80028. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  80029. * This is usefull at run time to apply the good shader.
  80030. */
  80031. _this.isPMREM = false;
  80032. _this._isBlocking = true;
  80033. _this._rotationY = 0;
  80034. /**
  80035. * Gets or sets the center of the bounding box associated with the cube texture
  80036. * It must define where the camera used to render the texture was set
  80037. */
  80038. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80039. if (!url) {
  80040. return _this;
  80041. }
  80042. _this.name = url;
  80043. _this.url = url;
  80044. _this.hasAlpha = false;
  80045. _this.isCube = true;
  80046. _this._textureMatrix = BABYLON.Matrix.Identity();
  80047. _this._onLoad = onLoad;
  80048. _this._onError = onError;
  80049. _this.gammaSpace = false;
  80050. var caps = scene.getEngine().getCaps();
  80051. if (size) {
  80052. _this._isBABYLONPreprocessed = false;
  80053. _this._noMipmap = noMipmap;
  80054. _this._size = size;
  80055. _this._useInGammaSpace = useInGammaSpace;
  80056. _this._usePMREMGenerator = usePMREMGenerator &&
  80057. caps.textureLOD &&
  80058. caps.textureFloat &&
  80059. !_this._useInGammaSpace;
  80060. }
  80061. else {
  80062. _this._isBABYLONPreprocessed = true;
  80063. _this._noMipmap = false;
  80064. _this._useInGammaSpace = false;
  80065. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  80066. !_this._useInGammaSpace;
  80067. }
  80068. _this.isPMREM = _this._usePMREMGenerator;
  80069. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80070. if (!_this._texture) {
  80071. if (!scene.useDelayedTextureLoading) {
  80072. _this.loadTexture();
  80073. }
  80074. else {
  80075. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80076. }
  80077. }
  80078. return _this;
  80079. }
  80080. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80081. /**
  80082. * Gets wether or not the texture is blocking during loading.
  80083. */
  80084. get: function () {
  80085. return this._isBlocking;
  80086. },
  80087. /**
  80088. * Sets wether or not the texture is blocking during loading.
  80089. */
  80090. set: function (value) {
  80091. this._isBlocking = value;
  80092. },
  80093. enumerable: true,
  80094. configurable: true
  80095. });
  80096. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80097. /**
  80098. * Gets texture matrix rotation angle around Y axis radians.
  80099. */
  80100. get: function () {
  80101. return this._rotationY;
  80102. },
  80103. /**
  80104. * Sets texture matrix rotation angle around Y axis in radians.
  80105. */
  80106. set: function (value) {
  80107. this._rotationY = value;
  80108. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80109. },
  80110. enumerable: true,
  80111. configurable: true
  80112. });
  80113. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80114. get: function () {
  80115. return this._boundingBoxSize;
  80116. },
  80117. /**
  80118. * Gets or sets the size of the bounding box associated with the cube texture
  80119. * When defined, the cubemap will switch to local mode
  80120. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80121. * @example https://www.babylonjs-playground.com/#RNASML
  80122. */
  80123. set: function (value) {
  80124. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80125. return;
  80126. }
  80127. this._boundingBoxSize = value;
  80128. var scene = this.getScene();
  80129. if (scene) {
  80130. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80131. }
  80132. },
  80133. enumerable: true,
  80134. configurable: true
  80135. });
  80136. /**
  80137. * Occurs when the file is a preprocessed .babylon.hdr file.
  80138. */
  80139. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  80140. var _this = this;
  80141. var mipLevels = 0;
  80142. var floatArrayView = null;
  80143. var scene = this.getScene();
  80144. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  80145. var mips = new Array();
  80146. if (!floatArrayView) {
  80147. return mips;
  80148. }
  80149. var startIndex = 30;
  80150. for (var level = 0; level < mipLevels; level++) {
  80151. mips.push([]);
  80152. // Fill each pixel of the mip level.
  80153. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  80154. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80155. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  80156. mips[level].push(faceData);
  80157. startIndex += faceSize;
  80158. }
  80159. }
  80160. return mips;
  80161. } : null;
  80162. var callback = function (buffer) {
  80163. var scene = _this.getScene();
  80164. if (!scene) {
  80165. return null;
  80166. }
  80167. // Create Native Array Views
  80168. var intArrayView = new Int32Array(buffer);
  80169. floatArrayView = new Float32Array(buffer);
  80170. // Fill header.
  80171. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  80172. _this._size = intArrayView[1]; // CubeMap max mip face size.
  80173. // Update Texture Information.
  80174. if (!_this._texture) {
  80175. return null;
  80176. }
  80177. _this._texture.updateSize(_this._size, _this._size);
  80178. // Fill polynomial information.
  80179. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  80180. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  80181. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  80182. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  80183. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  80184. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  80185. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  80186. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  80187. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  80188. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  80189. _this.sphericalPolynomial = sphericalPolynomial;
  80190. // Fill pixel data.
  80191. mipLevels = intArrayView[29]; // Number of mip levels.
  80192. var startIndex = 30;
  80193. var data = [];
  80194. var faceSize = Math.pow(_this._size, 2) * 3;
  80195. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80196. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  80197. startIndex += faceSize;
  80198. }
  80199. var results = [];
  80200. var byteArray = null;
  80201. // Push each faces.
  80202. for (var k = 0; k < 6; k++) {
  80203. var dataFace = null;
  80204. // To be deprecated.
  80205. if (version === 1) {
  80206. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  80207. dataFace = data[j];
  80208. }
  80209. // If special cases.
  80210. if (!mipmapGenerator && dataFace) {
  80211. if (!scene.getEngine().getCaps().textureFloat) {
  80212. // 3 channels of 1 bytes per pixel in bytes.
  80213. var byteBuffer = new ArrayBuffer(faceSize);
  80214. byteArray = new Uint8Array(byteBuffer);
  80215. }
  80216. for (var i = 0; i < _this._size * _this._size; i++) {
  80217. // Put in gamma space if requested.
  80218. if (_this._useInGammaSpace) {
  80219. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80220. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80221. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80222. }
  80223. // Convert to int texture for fallback.
  80224. if (byteArray) {
  80225. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80226. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80227. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80228. // May use luminance instead if the result is not accurate.
  80229. var max = Math.max(Math.max(r, g), b);
  80230. if (max > 255) {
  80231. var scale = 255 / max;
  80232. r *= scale;
  80233. g *= scale;
  80234. b *= scale;
  80235. }
  80236. byteArray[(i * 3) + 0] = r;
  80237. byteArray[(i * 3) + 1] = g;
  80238. byteArray[(i * 3) + 2] = b;
  80239. }
  80240. }
  80241. }
  80242. // Fill the array accordingly.
  80243. if (byteArray) {
  80244. results.push(byteArray);
  80245. }
  80246. else {
  80247. results.push(dataFace);
  80248. }
  80249. }
  80250. return results;
  80251. };
  80252. if (scene) {
  80253. 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, mipmapGenerator, this._onLoad, this._onError);
  80254. }
  80255. };
  80256. /**
  80257. * Occurs when the file is raw .hdr file.
  80258. */
  80259. HDRCubeTexture.prototype.loadHDRTexture = function () {
  80260. var _this = this;
  80261. var callback = function (buffer) {
  80262. var scene = _this.getScene();
  80263. if (!scene) {
  80264. return null;
  80265. }
  80266. // Extract the raw linear data.
  80267. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80268. // Generate harmonics if needed.
  80269. if (_this._generateHarmonics) {
  80270. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80271. _this.sphericalPolynomial = sphericalPolynomial;
  80272. }
  80273. var results = [];
  80274. var byteArray = null;
  80275. // Push each faces.
  80276. for (var j = 0; j < 6; j++) {
  80277. // Create uintarray fallback.
  80278. if (!scene.getEngine().getCaps().textureFloat) {
  80279. // 3 channels of 1 bytes per pixel in bytes.
  80280. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80281. byteArray = new Uint8Array(byteBuffer);
  80282. }
  80283. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80284. // If special cases.
  80285. if (_this._useInGammaSpace || byteArray) {
  80286. for (var i = 0; i < _this._size * _this._size; i++) {
  80287. // Put in gamma space if requested.
  80288. if (_this._useInGammaSpace) {
  80289. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80290. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80291. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80292. }
  80293. // Convert to int texture for fallback.
  80294. if (byteArray) {
  80295. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80296. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80297. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80298. // May use luminance instead if the result is not accurate.
  80299. var max = Math.max(Math.max(r, g), b);
  80300. if (max > 255) {
  80301. var scale = 255 / max;
  80302. r *= scale;
  80303. g *= scale;
  80304. b *= scale;
  80305. }
  80306. byteArray[(i * 3) + 0] = r;
  80307. byteArray[(i * 3) + 1] = g;
  80308. byteArray[(i * 3) + 2] = b;
  80309. }
  80310. }
  80311. }
  80312. if (byteArray) {
  80313. results.push(byteArray);
  80314. }
  80315. else {
  80316. results.push(dataFace);
  80317. }
  80318. }
  80319. return results;
  80320. };
  80321. var mipmapGenerator = null;
  80322. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  80323. // if (!this._noMipmap &&
  80324. // this._usePMREMGenerator) {
  80325. // mipmapGenerator = (data: ArrayBufferView[]) => {
  80326. // // Custom setup of the generator matching with the PBR shader values.
  80327. // var generator = new BABYLON.PMREMGenerator(data,
  80328. // this._size,
  80329. // this._size,
  80330. // 0,
  80331. // 3,
  80332. // this.getScene().getEngine().getCaps().textureFloat,
  80333. // 2048,
  80334. // 0.25,
  80335. // false,
  80336. // true);
  80337. // return generator.filterCubeMap();
  80338. // };
  80339. // }
  80340. var scene = this.getScene();
  80341. if (scene) {
  80342. 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, mipmapGenerator, this._onLoad, this._onError);
  80343. }
  80344. };
  80345. /**
  80346. * Starts the loading process of the texture.
  80347. */
  80348. HDRCubeTexture.prototype.loadTexture = function () {
  80349. if (this._isBABYLONPreprocessed) {
  80350. this.loadBabylonTexture();
  80351. }
  80352. else {
  80353. this.loadHDRTexture();
  80354. }
  80355. };
  80356. HDRCubeTexture.prototype.clone = function () {
  80357. var scene = this.getScene();
  80358. if (!scene) {
  80359. return this;
  80360. }
  80361. var size = (this._isBABYLONPreprocessed ? null : this._size);
  80362. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  80363. // Base texture
  80364. newTexture.level = this.level;
  80365. newTexture.wrapU = this.wrapU;
  80366. newTexture.wrapV = this.wrapV;
  80367. newTexture.coordinatesIndex = this.coordinatesIndex;
  80368. newTexture.coordinatesMode = this.coordinatesMode;
  80369. return newTexture;
  80370. };
  80371. // Methods
  80372. HDRCubeTexture.prototype.delayLoad = function () {
  80373. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80374. return;
  80375. }
  80376. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80377. this._texture = this._getFromCache(this.url, this._noMipmap);
  80378. if (!this._texture) {
  80379. this.loadTexture();
  80380. }
  80381. };
  80382. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80383. return this._textureMatrix;
  80384. };
  80385. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80386. this._textureMatrix = value;
  80387. };
  80388. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80389. var texture = null;
  80390. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80391. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  80392. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  80393. texture.name = parsedTexture.name;
  80394. texture.hasAlpha = parsedTexture.hasAlpha;
  80395. texture.level = parsedTexture.level;
  80396. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80397. texture.isBlocking = parsedTexture.isBlocking;
  80398. }
  80399. if (texture) {
  80400. if (parsedTexture.boundingBoxPosition) {
  80401. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80402. }
  80403. if (parsedTexture.boundingBoxSize) {
  80404. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80405. }
  80406. if (parsedTexture.rotationY) {
  80407. texture.rotationY = parsedTexture.rotationY;
  80408. }
  80409. }
  80410. return texture;
  80411. };
  80412. HDRCubeTexture.prototype.serialize = function () {
  80413. if (!this.name) {
  80414. return null;
  80415. }
  80416. var serializationObject = {};
  80417. serializationObject.name = this.name;
  80418. serializationObject.hasAlpha = this.hasAlpha;
  80419. serializationObject.isCube = true;
  80420. serializationObject.level = this.level;
  80421. serializationObject.size = this._size;
  80422. serializationObject.coordinatesMode = this.coordinatesMode;
  80423. serializationObject.useInGammaSpace = this._useInGammaSpace;
  80424. serializationObject.generateHarmonics = this._generateHarmonics;
  80425. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  80426. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  80427. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80428. serializationObject.noMipmap = this._noMipmap;
  80429. serializationObject.isBlocking = this._isBlocking;
  80430. serializationObject.rotationY = this._rotationY;
  80431. return serializationObject;
  80432. };
  80433. /**
  80434. * Saves as a file the data contained in the texture in a binary format.
  80435. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80436. * as the spherical used in the lighting.
  80437. * @param url The HDR file url.
  80438. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80439. * @param onError Method called if any error happens during download.
  80440. * @return The packed binary data.
  80441. */
  80442. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  80443. if (onError === void 0) { onError = null; }
  80444. var callback = function (buffer) {
  80445. var data = new Blob([buffer], { type: 'application/octet-stream' });
  80446. // Returns a URL you can use as a href.
  80447. var objUrl = window.URL.createObjectURL(data);
  80448. // Simulates a link to it and click to dowload.
  80449. var a = document.createElement("a");
  80450. document.body.appendChild(a);
  80451. a.style.display = "none";
  80452. a.href = objUrl;
  80453. a.download = "envmap.babylon.hdr";
  80454. a.click();
  80455. };
  80456. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  80457. };
  80458. /**
  80459. * Serializes the data contained in the texture in a binary format.
  80460. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80461. * as the spherical used in the lighting.
  80462. * @param url The HDR file url.
  80463. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80464. * @param onError Method called if any error happens during download.
  80465. * @return The packed binary data.
  80466. */
  80467. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  80468. if (onError === void 0) { onError = null; }
  80469. // Needs the url tho create the texture.
  80470. if (!url) {
  80471. return;
  80472. }
  80473. // Check Power of two size.
  80474. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  80475. return;
  80476. }
  80477. // Coming Back in 3.x.
  80478. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  80479. };
  80480. HDRCubeTexture._facesMapping = [
  80481. "right",
  80482. "left",
  80483. "up",
  80484. "down",
  80485. "front",
  80486. "back"
  80487. ];
  80488. return HDRCubeTexture;
  80489. }(BABYLON.BaseTexture));
  80490. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80491. })(BABYLON || (BABYLON = {}));
  80492. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80493. var BABYLON;
  80494. (function (BABYLON) {
  80495. var IndexedVector2 = /** @class */ (function (_super) {
  80496. __extends(IndexedVector2, _super);
  80497. function IndexedVector2(original, index) {
  80498. var _this = _super.call(this, original.x, original.y) || this;
  80499. _this.index = index;
  80500. return _this;
  80501. }
  80502. return IndexedVector2;
  80503. }(BABYLON.Vector2));
  80504. var PolygonPoints = /** @class */ (function () {
  80505. function PolygonPoints() {
  80506. this.elements = new Array();
  80507. }
  80508. PolygonPoints.prototype.add = function (originalPoints) {
  80509. var _this = this;
  80510. var result = new Array();
  80511. originalPoints.forEach(function (point) {
  80512. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80513. var newPoint = new IndexedVector2(point, _this.elements.length);
  80514. result.push(newPoint);
  80515. _this.elements.push(newPoint);
  80516. }
  80517. });
  80518. return result;
  80519. };
  80520. PolygonPoints.prototype.computeBounds = function () {
  80521. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80522. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80523. this.elements.forEach(function (point) {
  80524. // x
  80525. if (point.x < lmin.x) {
  80526. lmin.x = point.x;
  80527. }
  80528. else if (point.x > lmax.x) {
  80529. lmax.x = point.x;
  80530. }
  80531. // y
  80532. if (point.y < lmin.y) {
  80533. lmin.y = point.y;
  80534. }
  80535. else if (point.y > lmax.y) {
  80536. lmax.y = point.y;
  80537. }
  80538. });
  80539. return {
  80540. min: lmin,
  80541. max: lmax,
  80542. width: lmax.x - lmin.x,
  80543. height: lmax.y - lmin.y
  80544. };
  80545. };
  80546. return PolygonPoints;
  80547. }());
  80548. var Polygon = /** @class */ (function () {
  80549. function Polygon() {
  80550. }
  80551. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80552. return [
  80553. new BABYLON.Vector2(xmin, ymin),
  80554. new BABYLON.Vector2(xmax, ymin),
  80555. new BABYLON.Vector2(xmax, ymax),
  80556. new BABYLON.Vector2(xmin, ymax)
  80557. ];
  80558. };
  80559. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80560. if (cx === void 0) { cx = 0; }
  80561. if (cy === void 0) { cy = 0; }
  80562. if (numberOfSides === void 0) { numberOfSides = 32; }
  80563. var result = new Array();
  80564. var angle = 0;
  80565. var increment = (Math.PI * 2) / numberOfSides;
  80566. for (var i = 0; i < numberOfSides; i++) {
  80567. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80568. angle -= increment;
  80569. }
  80570. return result;
  80571. };
  80572. Polygon.Parse = function (input) {
  80573. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80574. var i, result = [];
  80575. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80576. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80577. }
  80578. return result;
  80579. };
  80580. Polygon.StartingAt = function (x, y) {
  80581. return BABYLON.Path2.StartingAt(x, y);
  80582. };
  80583. return Polygon;
  80584. }());
  80585. BABYLON.Polygon = Polygon;
  80586. var PolygonMeshBuilder = /** @class */ (function () {
  80587. function PolygonMeshBuilder(name, contours, scene) {
  80588. this._points = new PolygonPoints();
  80589. this._outlinepoints = new PolygonPoints();
  80590. this._holes = new Array();
  80591. this._epoints = new Array();
  80592. this._eholes = new Array();
  80593. this._name = name;
  80594. this._scene = scene;
  80595. var points;
  80596. if (contours instanceof BABYLON.Path2) {
  80597. points = contours.getPoints();
  80598. }
  80599. else {
  80600. points = contours;
  80601. }
  80602. this._addToepoint(points);
  80603. this._points.add(points);
  80604. this._outlinepoints.add(points);
  80605. if (typeof earcut === 'undefined') {
  80606. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80607. }
  80608. }
  80609. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80610. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80611. var p = points_1[_i];
  80612. this._epoints.push(p.x, p.y);
  80613. }
  80614. };
  80615. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80616. this._points.add(hole);
  80617. var holepoints = new PolygonPoints();
  80618. holepoints.add(hole);
  80619. this._holes.push(holepoints);
  80620. this._eholes.push(this._epoints.length / 2);
  80621. this._addToepoint(hole);
  80622. return this;
  80623. };
  80624. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80625. var _this = this;
  80626. if (updatable === void 0) { updatable = false; }
  80627. if (depth === void 0) { depth = 0; }
  80628. var result = new BABYLON.Mesh(this._name, this._scene);
  80629. var normals = new Array();
  80630. var positions = new Array();
  80631. var uvs = new Array();
  80632. var bounds = this._points.computeBounds();
  80633. this._points.elements.forEach(function (p) {
  80634. normals.push(0, 1.0, 0);
  80635. positions.push(p.x, 0, p.y);
  80636. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80637. });
  80638. var indices = new Array();
  80639. var res = earcut(this._epoints, this._eholes, 2);
  80640. for (var i = 0; i < res.length; i++) {
  80641. indices.push(res[i]);
  80642. }
  80643. if (depth > 0) {
  80644. var positionscount = (positions.length / 3); //get the current pointcount
  80645. this._points.elements.forEach(function (p) {
  80646. normals.push(0, -1.0, 0);
  80647. positions.push(p.x, -depth, p.y);
  80648. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80649. });
  80650. var totalCount = indices.length;
  80651. for (var i = 0; i < totalCount; i += 3) {
  80652. var i0 = indices[i + 0];
  80653. var i1 = indices[i + 1];
  80654. var i2 = indices[i + 2];
  80655. indices.push(i2 + positionscount);
  80656. indices.push(i1 + positionscount);
  80657. indices.push(i0 + positionscount);
  80658. }
  80659. //Add the sides
  80660. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80661. this._holes.forEach(function (hole) {
  80662. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80663. });
  80664. }
  80665. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80666. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80667. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80668. result.setIndices(indices);
  80669. return result;
  80670. };
  80671. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80672. var StartIndex = positions.length / 3;
  80673. var ulength = 0;
  80674. for (var i = 0; i < points.elements.length; i++) {
  80675. var p = points.elements[i];
  80676. var p1;
  80677. if ((i + 1) > points.elements.length - 1) {
  80678. p1 = points.elements[0];
  80679. }
  80680. else {
  80681. p1 = points.elements[i + 1];
  80682. }
  80683. positions.push(p.x, 0, p.y);
  80684. positions.push(p.x, -depth, p.y);
  80685. positions.push(p1.x, 0, p1.y);
  80686. positions.push(p1.x, -depth, p1.y);
  80687. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80688. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80689. var v3 = v2.subtract(v1);
  80690. var v4 = new BABYLON.Vector3(0, 1, 0);
  80691. var vn = BABYLON.Vector3.Cross(v3, v4);
  80692. vn = vn.normalize();
  80693. uvs.push(ulength / bounds.width, 0);
  80694. uvs.push(ulength / bounds.width, 1);
  80695. ulength += v3.length();
  80696. uvs.push((ulength / bounds.width), 0);
  80697. uvs.push((ulength / bounds.width), 1);
  80698. if (!flip) {
  80699. normals.push(-vn.x, -vn.y, -vn.z);
  80700. normals.push(-vn.x, -vn.y, -vn.z);
  80701. normals.push(-vn.x, -vn.y, -vn.z);
  80702. normals.push(-vn.x, -vn.y, -vn.z);
  80703. indices.push(StartIndex);
  80704. indices.push(StartIndex + 1);
  80705. indices.push(StartIndex + 2);
  80706. indices.push(StartIndex + 1);
  80707. indices.push(StartIndex + 3);
  80708. indices.push(StartIndex + 2);
  80709. }
  80710. else {
  80711. normals.push(vn.x, vn.y, vn.z);
  80712. normals.push(vn.x, vn.y, vn.z);
  80713. normals.push(vn.x, vn.y, vn.z);
  80714. normals.push(vn.x, vn.y, vn.z);
  80715. indices.push(StartIndex);
  80716. indices.push(StartIndex + 2);
  80717. indices.push(StartIndex + 1);
  80718. indices.push(StartIndex + 1);
  80719. indices.push(StartIndex + 2);
  80720. indices.push(StartIndex + 3);
  80721. }
  80722. StartIndex += 4;
  80723. }
  80724. ;
  80725. };
  80726. return PolygonMeshBuilder;
  80727. }());
  80728. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80729. })(BABYLON || (BABYLON = {}));
  80730. //# sourceMappingURL=babylon.polygonMesh.js.map
  80731. var BABYLON;
  80732. (function (BABYLON) {
  80733. // Unique ID when we import meshes from Babylon to CSG
  80734. var currentCSGMeshId = 0;
  80735. // # class Vertex
  80736. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80737. // one to provide additional features like texture coordinates and vertex
  80738. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80739. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80740. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80741. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80742. // is not used anywhere else.
  80743. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80744. var Vertex = /** @class */ (function () {
  80745. function Vertex(pos, normal, uv) {
  80746. this.pos = pos;
  80747. this.normal = normal;
  80748. this.uv = uv;
  80749. }
  80750. Vertex.prototype.clone = function () {
  80751. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80752. };
  80753. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80754. // orientation of a polygon is flipped.
  80755. Vertex.prototype.flip = function () {
  80756. this.normal = this.normal.scale(-1);
  80757. };
  80758. // Create a new vertex between this vertex and `other` by linearly
  80759. // interpolating all properties using a parameter of `t`. Subclasses should
  80760. // override this to interpolate additional properties.
  80761. Vertex.prototype.interpolate = function (other, t) {
  80762. 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));
  80763. };
  80764. return Vertex;
  80765. }());
  80766. // # class Plane
  80767. // Represents a plane in 3D space.
  80768. var Plane = /** @class */ (function () {
  80769. function Plane(normal, w) {
  80770. this.normal = normal;
  80771. this.w = w;
  80772. }
  80773. Plane.FromPoints = function (a, b, c) {
  80774. var v0 = c.subtract(a);
  80775. var v1 = b.subtract(a);
  80776. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80777. return null;
  80778. }
  80779. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80780. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80781. };
  80782. Plane.prototype.clone = function () {
  80783. return new Plane(this.normal.clone(), this.w);
  80784. };
  80785. Plane.prototype.flip = function () {
  80786. this.normal.scaleInPlace(-1);
  80787. this.w = -this.w;
  80788. };
  80789. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80790. // fragments in the appropriate lists. Coplanar polygons go into either
  80791. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80792. // respect to this plane. Polygons in front or in back of this plane go into
  80793. // either `front` or `back`.
  80794. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80795. var COPLANAR = 0;
  80796. var FRONT = 1;
  80797. var BACK = 2;
  80798. var SPANNING = 3;
  80799. // Classify each point as well as the entire polygon into one of the above
  80800. // four classes.
  80801. var polygonType = 0;
  80802. var types = [];
  80803. var i;
  80804. var t;
  80805. for (i = 0; i < polygon.vertices.length; i++) {
  80806. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80807. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80808. polygonType |= type;
  80809. types.push(type);
  80810. }
  80811. // Put the polygon in the correct list, splitting it when necessary.
  80812. switch (polygonType) {
  80813. case COPLANAR:
  80814. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80815. break;
  80816. case FRONT:
  80817. front.push(polygon);
  80818. break;
  80819. case BACK:
  80820. back.push(polygon);
  80821. break;
  80822. case SPANNING:
  80823. var f = [], b = [];
  80824. for (i = 0; i < polygon.vertices.length; i++) {
  80825. var j = (i + 1) % polygon.vertices.length;
  80826. var ti = types[i], tj = types[j];
  80827. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80828. if (ti !== BACK)
  80829. f.push(vi);
  80830. if (ti !== FRONT)
  80831. b.push(ti !== BACK ? vi.clone() : vi);
  80832. if ((ti | tj) === SPANNING) {
  80833. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80834. var v = vi.interpolate(vj, t);
  80835. f.push(v);
  80836. b.push(v.clone());
  80837. }
  80838. }
  80839. var poly;
  80840. if (f.length >= 3) {
  80841. poly = new Polygon(f, polygon.shared);
  80842. if (poly.plane)
  80843. front.push(poly);
  80844. }
  80845. if (b.length >= 3) {
  80846. poly = new Polygon(b, polygon.shared);
  80847. if (poly.plane)
  80848. back.push(poly);
  80849. }
  80850. break;
  80851. }
  80852. };
  80853. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80854. // point is on the plane.
  80855. Plane.EPSILON = 1e-5;
  80856. return Plane;
  80857. }());
  80858. // # class Polygon
  80859. // Represents a convex polygon. The vertices used to initialize a polygon must
  80860. // be coplanar and form a convex loop.
  80861. //
  80862. // Each convex polygon has a `shared` property, which is shared between all
  80863. // polygons that are clones of each other or were split from the same polygon.
  80864. // This can be used to define per-polygon properties (such as surface color).
  80865. var Polygon = /** @class */ (function () {
  80866. function Polygon(vertices, shared) {
  80867. this.vertices = vertices;
  80868. this.shared = shared;
  80869. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80870. }
  80871. Polygon.prototype.clone = function () {
  80872. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80873. return new Polygon(vertices, this.shared);
  80874. };
  80875. Polygon.prototype.flip = function () {
  80876. this.vertices.reverse().map(function (v) { v.flip(); });
  80877. this.plane.flip();
  80878. };
  80879. return Polygon;
  80880. }());
  80881. // # class Node
  80882. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80883. // by picking a polygon to split along. That polygon (and all other coplanar
  80884. // polygons) are added directly to that node and the other polygons are added to
  80885. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80886. // no distinction between internal and leaf nodes.
  80887. var Node = /** @class */ (function () {
  80888. function Node(polygons) {
  80889. this.plane = null;
  80890. this.front = null;
  80891. this.back = null;
  80892. this.polygons = new Array();
  80893. if (polygons) {
  80894. this.build(polygons);
  80895. }
  80896. }
  80897. Node.prototype.clone = function () {
  80898. var node = new Node();
  80899. node.plane = this.plane && this.plane.clone();
  80900. node.front = this.front && this.front.clone();
  80901. node.back = this.back && this.back.clone();
  80902. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80903. return node;
  80904. };
  80905. // Convert solid space to empty space and empty space to solid space.
  80906. Node.prototype.invert = function () {
  80907. for (var i = 0; i < this.polygons.length; i++) {
  80908. this.polygons[i].flip();
  80909. }
  80910. if (this.plane) {
  80911. this.plane.flip();
  80912. }
  80913. if (this.front) {
  80914. this.front.invert();
  80915. }
  80916. if (this.back) {
  80917. this.back.invert();
  80918. }
  80919. var temp = this.front;
  80920. this.front = this.back;
  80921. this.back = temp;
  80922. };
  80923. // Recursively remove all polygons in `polygons` that are inside this BSP
  80924. // tree.
  80925. Node.prototype.clipPolygons = function (polygons) {
  80926. if (!this.plane)
  80927. return polygons.slice();
  80928. var front = new Array(), back = new Array();
  80929. for (var i = 0; i < polygons.length; i++) {
  80930. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80931. }
  80932. if (this.front) {
  80933. front = this.front.clipPolygons(front);
  80934. }
  80935. if (this.back) {
  80936. back = this.back.clipPolygons(back);
  80937. }
  80938. else {
  80939. back = [];
  80940. }
  80941. return front.concat(back);
  80942. };
  80943. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80944. // `bsp`.
  80945. Node.prototype.clipTo = function (bsp) {
  80946. this.polygons = bsp.clipPolygons(this.polygons);
  80947. if (this.front)
  80948. this.front.clipTo(bsp);
  80949. if (this.back)
  80950. this.back.clipTo(bsp);
  80951. };
  80952. // Return a list of all polygons in this BSP tree.
  80953. Node.prototype.allPolygons = function () {
  80954. var polygons = this.polygons.slice();
  80955. if (this.front)
  80956. polygons = polygons.concat(this.front.allPolygons());
  80957. if (this.back)
  80958. polygons = polygons.concat(this.back.allPolygons());
  80959. return polygons;
  80960. };
  80961. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80962. // new polygons are filtered down to the bottom of the tree and become new
  80963. // nodes there. Each set of polygons is partitioned using the first polygon
  80964. // (no heuristic is used to pick a good split).
  80965. Node.prototype.build = function (polygons) {
  80966. if (!polygons.length)
  80967. return;
  80968. if (!this.plane)
  80969. this.plane = polygons[0].plane.clone();
  80970. var front = new Array(), back = new Array();
  80971. for (var i = 0; i < polygons.length; i++) {
  80972. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80973. }
  80974. if (front.length) {
  80975. if (!this.front)
  80976. this.front = new Node();
  80977. this.front.build(front);
  80978. }
  80979. if (back.length) {
  80980. if (!this.back)
  80981. this.back = new Node();
  80982. this.back.build(back);
  80983. }
  80984. };
  80985. return Node;
  80986. }());
  80987. var CSG = /** @class */ (function () {
  80988. function CSG() {
  80989. this.polygons = new Array();
  80990. }
  80991. // Convert BABYLON.Mesh to BABYLON.CSG
  80992. CSG.FromMesh = function (mesh) {
  80993. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80994. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80995. if (mesh instanceof BABYLON.Mesh) {
  80996. mesh.computeWorldMatrix(true);
  80997. matrix = mesh.getWorldMatrix();
  80998. meshPosition = mesh.position.clone();
  80999. meshRotation = mesh.rotation.clone();
  81000. if (mesh.rotationQuaternion) {
  81001. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81002. }
  81003. meshScaling = mesh.scaling.clone();
  81004. }
  81005. else {
  81006. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81007. }
  81008. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81009. var subMeshes = mesh.subMeshes;
  81010. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81011. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81012. vertices = [];
  81013. for (var j = 0; j < 3; j++) {
  81014. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81015. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81016. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81017. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81018. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81019. vertex = new Vertex(position, normal, uv);
  81020. vertices.push(vertex);
  81021. }
  81022. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81023. // To handle the case of degenerated triangle
  81024. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81025. if (polygon.plane)
  81026. polygons.push(polygon);
  81027. }
  81028. }
  81029. var csg = CSG.FromPolygons(polygons);
  81030. csg.matrix = matrix;
  81031. csg.position = meshPosition;
  81032. csg.rotation = meshRotation;
  81033. csg.scaling = meshScaling;
  81034. csg.rotationQuaternion = meshRotationQuaternion;
  81035. currentCSGMeshId++;
  81036. return csg;
  81037. };
  81038. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81039. CSG.FromPolygons = function (polygons) {
  81040. var csg = new CSG();
  81041. csg.polygons = polygons;
  81042. return csg;
  81043. };
  81044. CSG.prototype.clone = function () {
  81045. var csg = new CSG();
  81046. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81047. csg.copyTransformAttributes(this);
  81048. return csg;
  81049. };
  81050. CSG.prototype.union = function (csg) {
  81051. var a = new Node(this.clone().polygons);
  81052. var b = new Node(csg.clone().polygons);
  81053. a.clipTo(b);
  81054. b.clipTo(a);
  81055. b.invert();
  81056. b.clipTo(a);
  81057. b.invert();
  81058. a.build(b.allPolygons());
  81059. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81060. };
  81061. CSG.prototype.unionInPlace = function (csg) {
  81062. var a = new Node(this.polygons);
  81063. var b = new Node(csg.polygons);
  81064. a.clipTo(b);
  81065. b.clipTo(a);
  81066. b.invert();
  81067. b.clipTo(a);
  81068. b.invert();
  81069. a.build(b.allPolygons());
  81070. this.polygons = a.allPolygons();
  81071. };
  81072. CSG.prototype.subtract = function (csg) {
  81073. var a = new Node(this.clone().polygons);
  81074. var b = new Node(csg.clone().polygons);
  81075. a.invert();
  81076. a.clipTo(b);
  81077. b.clipTo(a);
  81078. b.invert();
  81079. b.clipTo(a);
  81080. b.invert();
  81081. a.build(b.allPolygons());
  81082. a.invert();
  81083. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81084. };
  81085. CSG.prototype.subtractInPlace = function (csg) {
  81086. var a = new Node(this.polygons);
  81087. var b = new Node(csg.polygons);
  81088. a.invert();
  81089. a.clipTo(b);
  81090. b.clipTo(a);
  81091. b.invert();
  81092. b.clipTo(a);
  81093. b.invert();
  81094. a.build(b.allPolygons());
  81095. a.invert();
  81096. this.polygons = a.allPolygons();
  81097. };
  81098. CSG.prototype.intersect = function (csg) {
  81099. var a = new Node(this.clone().polygons);
  81100. var b = new Node(csg.clone().polygons);
  81101. a.invert();
  81102. b.clipTo(a);
  81103. b.invert();
  81104. a.clipTo(b);
  81105. b.clipTo(a);
  81106. a.build(b.allPolygons());
  81107. a.invert();
  81108. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81109. };
  81110. CSG.prototype.intersectInPlace = function (csg) {
  81111. var a = new Node(this.polygons);
  81112. var b = new Node(csg.polygons);
  81113. a.invert();
  81114. b.clipTo(a);
  81115. b.invert();
  81116. a.clipTo(b);
  81117. b.clipTo(a);
  81118. a.build(b.allPolygons());
  81119. a.invert();
  81120. this.polygons = a.allPolygons();
  81121. };
  81122. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81123. // not modified.
  81124. CSG.prototype.inverse = function () {
  81125. var csg = this.clone();
  81126. csg.inverseInPlace();
  81127. return csg;
  81128. };
  81129. CSG.prototype.inverseInPlace = function () {
  81130. this.polygons.map(function (p) { p.flip(); });
  81131. };
  81132. // This is used to keep meshes transformations so they can be restored
  81133. // when we build back a Babylon Mesh
  81134. // NB : All CSG operations are performed in world coordinates
  81135. CSG.prototype.copyTransformAttributes = function (csg) {
  81136. this.matrix = csg.matrix;
  81137. this.position = csg.position;
  81138. this.rotation = csg.rotation;
  81139. this.scaling = csg.scaling;
  81140. this.rotationQuaternion = csg.rotationQuaternion;
  81141. return this;
  81142. };
  81143. // Build Raw mesh from CSG
  81144. // Coordinates here are in world space
  81145. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81146. var matrix = this.matrix.clone();
  81147. matrix.invert();
  81148. 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;
  81149. if (keepSubMeshes) {
  81150. // Sort Polygons, since subMeshes are indices range
  81151. polygons.sort(function (a, b) {
  81152. if (a.shared.meshId === b.shared.meshId) {
  81153. return a.shared.subMeshId - b.shared.subMeshId;
  81154. }
  81155. else {
  81156. return a.shared.meshId - b.shared.meshId;
  81157. }
  81158. });
  81159. }
  81160. for (var i = 0, il = polygons.length; i < il; i++) {
  81161. polygon = polygons[i];
  81162. // Building SubMeshes
  81163. if (!subMesh_dict[polygon.shared.meshId]) {
  81164. subMesh_dict[polygon.shared.meshId] = {};
  81165. }
  81166. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81167. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81168. indexStart: +Infinity,
  81169. indexEnd: -Infinity,
  81170. materialIndex: polygon.shared.materialIndex
  81171. };
  81172. }
  81173. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81174. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81175. polygonIndices[0] = 0;
  81176. polygonIndices[1] = j - 1;
  81177. polygonIndices[2] = j;
  81178. for (var k = 0; k < 3; k++) {
  81179. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81180. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81181. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81182. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81183. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81184. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81185. // Check if 2 points can be merged
  81186. if (!(typeof vertex_idx !== 'undefined' &&
  81187. normals[vertex_idx * 3] === localNormal.x &&
  81188. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81189. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81190. uvs[vertex_idx * 2] === uv.x &&
  81191. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81192. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81193. uvs.push(uv.x, uv.y);
  81194. normals.push(normal.x, normal.y, normal.z);
  81195. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81196. }
  81197. indices.push(vertex_idx);
  81198. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81199. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81200. currentIndex++;
  81201. }
  81202. }
  81203. }
  81204. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81205. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81206. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81207. mesh.setIndices(indices, null);
  81208. if (keepSubMeshes) {
  81209. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81210. var materialIndexOffset = 0, materialMaxIndex;
  81211. mesh.subMeshes = new Array();
  81212. for (var m in subMesh_dict) {
  81213. materialMaxIndex = -1;
  81214. for (var sm in subMesh_dict[m]) {
  81215. subMesh_obj = subMesh_dict[m][sm];
  81216. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81217. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81218. }
  81219. materialIndexOffset += ++materialMaxIndex;
  81220. }
  81221. }
  81222. return mesh;
  81223. };
  81224. // Build Mesh from CSG taking material and transforms into account
  81225. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81226. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81227. mesh.material = material;
  81228. mesh.position.copyFrom(this.position);
  81229. mesh.rotation.copyFrom(this.rotation);
  81230. if (this.rotationQuaternion) {
  81231. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81232. }
  81233. mesh.scaling.copyFrom(this.scaling);
  81234. mesh.computeWorldMatrix(true);
  81235. return mesh;
  81236. };
  81237. return CSG;
  81238. }());
  81239. BABYLON.CSG = CSG;
  81240. })(BABYLON || (BABYLON = {}));
  81241. //# sourceMappingURL=babylon.csg.js.map
  81242. var BABYLON;
  81243. (function (BABYLON) {
  81244. var LensFlare = /** @class */ (function () {
  81245. function LensFlare(size, position, color, imgUrl, system) {
  81246. this.size = size;
  81247. this.position = position;
  81248. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81249. this.color = color || new BABYLON.Color3(1, 1, 1);
  81250. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81251. this._system = system;
  81252. system.lensFlares.push(this);
  81253. }
  81254. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81255. return new LensFlare(size, position, color, imgUrl, system);
  81256. };
  81257. LensFlare.prototype.dispose = function () {
  81258. if (this.texture) {
  81259. this.texture.dispose();
  81260. }
  81261. // Remove from scene
  81262. var index = this._system.lensFlares.indexOf(this);
  81263. this._system.lensFlares.splice(index, 1);
  81264. };
  81265. ;
  81266. return LensFlare;
  81267. }());
  81268. BABYLON.LensFlare = LensFlare;
  81269. })(BABYLON || (BABYLON = {}));
  81270. //# sourceMappingURL=babylon.lensFlare.js.map
  81271. var BABYLON;
  81272. (function (BABYLON) {
  81273. var LensFlareSystem = /** @class */ (function () {
  81274. function LensFlareSystem(name, emitter, scene) {
  81275. this.name = name;
  81276. this.lensFlares = new Array();
  81277. this.borderLimit = 300;
  81278. this.viewportBorder = 0;
  81279. this.layerMask = 0x0FFFFFFF;
  81280. this._vertexBuffers = {};
  81281. this._isEnabled = true;
  81282. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81283. this._emitter = emitter;
  81284. this.id = name;
  81285. scene.lensFlareSystems.push(this);
  81286. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81287. var engine = scene.getEngine();
  81288. // VBO
  81289. var vertices = [];
  81290. vertices.push(1, 1);
  81291. vertices.push(-1, 1);
  81292. vertices.push(-1, -1);
  81293. vertices.push(1, -1);
  81294. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81295. // Indices
  81296. var indices = [];
  81297. indices.push(0);
  81298. indices.push(1);
  81299. indices.push(2);
  81300. indices.push(0);
  81301. indices.push(2);
  81302. indices.push(3);
  81303. this._indexBuffer = engine.createIndexBuffer(indices);
  81304. // Effects
  81305. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81306. }
  81307. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81308. get: function () {
  81309. return this._isEnabled;
  81310. },
  81311. set: function (value) {
  81312. this._isEnabled = value;
  81313. },
  81314. enumerable: true,
  81315. configurable: true
  81316. });
  81317. LensFlareSystem.prototype.getScene = function () {
  81318. return this._scene;
  81319. };
  81320. LensFlareSystem.prototype.getEmitter = function () {
  81321. return this._emitter;
  81322. };
  81323. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81324. this._emitter = newEmitter;
  81325. };
  81326. LensFlareSystem.prototype.getEmitterPosition = function () {
  81327. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81328. };
  81329. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81330. var position = this.getEmitterPosition();
  81331. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81332. this._positionX = position.x;
  81333. this._positionY = position.y;
  81334. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81335. if (this.viewportBorder > 0) {
  81336. globalViewport.x -= this.viewportBorder;
  81337. globalViewport.y -= this.viewportBorder;
  81338. globalViewport.width += this.viewportBorder * 2;
  81339. globalViewport.height += this.viewportBorder * 2;
  81340. position.x += this.viewportBorder;
  81341. position.y += this.viewportBorder;
  81342. this._positionX += this.viewportBorder;
  81343. this._positionY += this.viewportBorder;
  81344. }
  81345. if (position.z > 0) {
  81346. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81347. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81348. return true;
  81349. }
  81350. return true;
  81351. }
  81352. return false;
  81353. };
  81354. LensFlareSystem.prototype._isVisible = function () {
  81355. if (!this._isEnabled || !this._scene.activeCamera) {
  81356. return false;
  81357. }
  81358. var emitterPosition = this.getEmitterPosition();
  81359. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81360. var distance = direction.length();
  81361. direction.normalize();
  81362. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81363. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81364. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81365. };
  81366. LensFlareSystem.prototype.render = function () {
  81367. if (!this._effect.isReady() || !this._scene.activeCamera)
  81368. return false;
  81369. var engine = this._scene.getEngine();
  81370. var viewport = this._scene.activeCamera.viewport;
  81371. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81372. // Position
  81373. if (!this.computeEffectivePosition(globalViewport)) {
  81374. return false;
  81375. }
  81376. // Visibility
  81377. if (!this._isVisible()) {
  81378. return false;
  81379. }
  81380. // Intensity
  81381. var awayX;
  81382. var awayY;
  81383. if (this._positionX < this.borderLimit + globalViewport.x) {
  81384. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81385. }
  81386. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81387. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81388. }
  81389. else {
  81390. awayX = 0;
  81391. }
  81392. if (this._positionY < this.borderLimit + globalViewport.y) {
  81393. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81394. }
  81395. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81396. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81397. }
  81398. else {
  81399. awayY = 0;
  81400. }
  81401. var away = (awayX > awayY) ? awayX : awayY;
  81402. away -= this.viewportBorder;
  81403. if (away > this.borderLimit) {
  81404. away = this.borderLimit;
  81405. }
  81406. var intensity = 1.0 - (away / this.borderLimit);
  81407. if (intensity < 0) {
  81408. return false;
  81409. }
  81410. if (intensity > 1.0) {
  81411. intensity = 1.0;
  81412. }
  81413. if (this.viewportBorder > 0) {
  81414. globalViewport.x += this.viewportBorder;
  81415. globalViewport.y += this.viewportBorder;
  81416. globalViewport.width -= this.viewportBorder * 2;
  81417. globalViewport.height -= this.viewportBorder * 2;
  81418. this._positionX -= this.viewportBorder;
  81419. this._positionY -= this.viewportBorder;
  81420. }
  81421. // Position
  81422. var centerX = globalViewport.x + globalViewport.width / 2;
  81423. var centerY = globalViewport.y + globalViewport.height / 2;
  81424. var distX = centerX - this._positionX;
  81425. var distY = centerY - this._positionY;
  81426. // Effects
  81427. engine.enableEffect(this._effect);
  81428. engine.setState(false);
  81429. engine.setDepthBuffer(false);
  81430. // VBOs
  81431. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81432. // Flares
  81433. for (var index = 0; index < this.lensFlares.length; index++) {
  81434. var flare = this.lensFlares[index];
  81435. engine.setAlphaMode(flare.alphaMode);
  81436. var x = centerX - (distX * flare.position);
  81437. var y = centerY - (distY * flare.position);
  81438. var cw = flare.size;
  81439. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81440. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81441. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81442. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81443. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81444. // Texture
  81445. this._effect.setTexture("textureSampler", flare.texture);
  81446. // Color
  81447. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81448. // Draw order
  81449. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81450. }
  81451. engine.setDepthBuffer(true);
  81452. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81453. return true;
  81454. };
  81455. LensFlareSystem.prototype.dispose = function () {
  81456. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81457. if (vertexBuffer) {
  81458. vertexBuffer.dispose();
  81459. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81460. }
  81461. if (this._indexBuffer) {
  81462. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81463. this._indexBuffer = null;
  81464. }
  81465. while (this.lensFlares.length) {
  81466. this.lensFlares[0].dispose();
  81467. }
  81468. // Remove from scene
  81469. var index = this._scene.lensFlareSystems.indexOf(this);
  81470. this._scene.lensFlareSystems.splice(index, 1);
  81471. };
  81472. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81473. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81474. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81475. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81476. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81477. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81478. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81479. var parsedFlare = parsedLensFlareSystem.flares[index];
  81480. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81481. }
  81482. return lensFlareSystem;
  81483. };
  81484. LensFlareSystem.prototype.serialize = function () {
  81485. var serializationObject = {};
  81486. serializationObject.id = this.id;
  81487. serializationObject.name = this.name;
  81488. serializationObject.emitterId = this.getEmitter().id;
  81489. serializationObject.borderLimit = this.borderLimit;
  81490. serializationObject.flares = [];
  81491. for (var index = 0; index < this.lensFlares.length; index++) {
  81492. var flare = this.lensFlares[index];
  81493. serializationObject.flares.push({
  81494. size: flare.size,
  81495. position: flare.position,
  81496. color: flare.color.asArray(),
  81497. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81498. });
  81499. }
  81500. return serializationObject;
  81501. };
  81502. return LensFlareSystem;
  81503. }());
  81504. BABYLON.LensFlareSystem = LensFlareSystem;
  81505. })(BABYLON || (BABYLON = {}));
  81506. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81507. var BABYLON;
  81508. (function (BABYLON) {
  81509. /**
  81510. * This is a holder class for the physics joint created by the physics plugin.
  81511. * It holds a set of functions to control the underlying joint.
  81512. */
  81513. var PhysicsJoint = /** @class */ (function () {
  81514. function PhysicsJoint(type, jointData) {
  81515. this.type = type;
  81516. this.jointData = jointData;
  81517. jointData.nativeParams = jointData.nativeParams || {};
  81518. }
  81519. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81520. get: function () {
  81521. return this._physicsJoint;
  81522. },
  81523. set: function (newJoint) {
  81524. if (this._physicsJoint) {
  81525. //remove from the wolrd
  81526. }
  81527. this._physicsJoint = newJoint;
  81528. },
  81529. enumerable: true,
  81530. configurable: true
  81531. });
  81532. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81533. set: function (physicsPlugin) {
  81534. this._physicsPlugin = physicsPlugin;
  81535. },
  81536. enumerable: true,
  81537. configurable: true
  81538. });
  81539. /**
  81540. * Execute a function that is physics-plugin specific.
  81541. * @param {Function} func the function that will be executed.
  81542. * It accepts two parameters: the physics world and the physics joint.
  81543. */
  81544. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81545. func(this._physicsPlugin.world, this._physicsJoint);
  81546. };
  81547. //TODO check if the native joints are the same
  81548. //Joint Types
  81549. PhysicsJoint.DistanceJoint = 0;
  81550. PhysicsJoint.HingeJoint = 1;
  81551. PhysicsJoint.BallAndSocketJoint = 2;
  81552. PhysicsJoint.WheelJoint = 3;
  81553. PhysicsJoint.SliderJoint = 4;
  81554. //OIMO
  81555. PhysicsJoint.PrismaticJoint = 5;
  81556. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81557. PhysicsJoint.UniversalJoint = 6;
  81558. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81559. //Cannon
  81560. //Similar to a Ball-Joint. Different in params
  81561. PhysicsJoint.PointToPointJoint = 8;
  81562. //Cannon only at the moment
  81563. PhysicsJoint.SpringJoint = 9;
  81564. PhysicsJoint.LockJoint = 10;
  81565. return PhysicsJoint;
  81566. }());
  81567. BABYLON.PhysicsJoint = PhysicsJoint;
  81568. /**
  81569. * A class representing a physics distance joint.
  81570. */
  81571. var DistanceJoint = /** @class */ (function (_super) {
  81572. __extends(DistanceJoint, _super);
  81573. function DistanceJoint(jointData) {
  81574. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81575. }
  81576. /**
  81577. * Update the predefined distance.
  81578. */
  81579. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81580. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81581. };
  81582. return DistanceJoint;
  81583. }(PhysicsJoint));
  81584. BABYLON.DistanceJoint = DistanceJoint;
  81585. var MotorEnabledJoint = /** @class */ (function (_super) {
  81586. __extends(MotorEnabledJoint, _super);
  81587. function MotorEnabledJoint(type, jointData) {
  81588. return _super.call(this, type, jointData) || this;
  81589. }
  81590. /**
  81591. * Set the motor values.
  81592. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81593. * @param {number} force the force to apply
  81594. * @param {number} maxForce max force for this motor.
  81595. */
  81596. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81597. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81598. };
  81599. /**
  81600. * Set the motor's limits.
  81601. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81602. */
  81603. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81604. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81605. };
  81606. return MotorEnabledJoint;
  81607. }(PhysicsJoint));
  81608. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81609. /**
  81610. * This class represents a single hinge physics joint
  81611. */
  81612. var HingeJoint = /** @class */ (function (_super) {
  81613. __extends(HingeJoint, _super);
  81614. function HingeJoint(jointData) {
  81615. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81616. }
  81617. /**
  81618. * Set the motor values.
  81619. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81620. * @param {number} force the force to apply
  81621. * @param {number} maxForce max force for this motor.
  81622. */
  81623. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81624. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81625. };
  81626. /**
  81627. * Set the motor's limits.
  81628. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81629. */
  81630. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81631. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81632. };
  81633. return HingeJoint;
  81634. }(MotorEnabledJoint));
  81635. BABYLON.HingeJoint = HingeJoint;
  81636. /**
  81637. * This class represents a dual hinge physics joint (same as wheel joint)
  81638. */
  81639. var Hinge2Joint = /** @class */ (function (_super) {
  81640. __extends(Hinge2Joint, _super);
  81641. function Hinge2Joint(jointData) {
  81642. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81643. }
  81644. /**
  81645. * Set the motor values.
  81646. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81647. * @param {number} force the force to apply
  81648. * @param {number} maxForce max force for this motor.
  81649. * @param {motorIndex} the motor's index, 0 or 1.
  81650. */
  81651. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81652. if (motorIndex === void 0) { motorIndex = 0; }
  81653. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81654. };
  81655. /**
  81656. * Set the motor limits.
  81657. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81658. * @param {number} upperLimit the upper limit
  81659. * @param {number} lowerLimit lower limit
  81660. * @param {motorIndex} the motor's index, 0 or 1.
  81661. */
  81662. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81663. if (motorIndex === void 0) { motorIndex = 0; }
  81664. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81665. };
  81666. return Hinge2Joint;
  81667. }(MotorEnabledJoint));
  81668. BABYLON.Hinge2Joint = Hinge2Joint;
  81669. })(BABYLON || (BABYLON = {}));
  81670. //# sourceMappingURL=babylon.physicsJoint.js.map
  81671. var BABYLON;
  81672. (function (BABYLON) {
  81673. var PhysicsImpostor = /** @class */ (function () {
  81674. function PhysicsImpostor(object, type, _options, _scene) {
  81675. if (_options === void 0) { _options = { mass: 0 }; }
  81676. var _this = this;
  81677. this.object = object;
  81678. this.type = type;
  81679. this._options = _options;
  81680. this._scene = _scene;
  81681. this._bodyUpdateRequired = false;
  81682. this._onBeforePhysicsStepCallbacks = new Array();
  81683. this._onAfterPhysicsStepCallbacks = new Array();
  81684. this._onPhysicsCollideCallbacks = [];
  81685. this._deltaPosition = BABYLON.Vector3.Zero();
  81686. this._isDisposed = false;
  81687. //temp variables for parent rotation calculations
  81688. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81689. this._tmpQuat = new BABYLON.Quaternion();
  81690. this._tmpQuat2 = new BABYLON.Quaternion();
  81691. /**
  81692. * this function is executed by the physics engine.
  81693. */
  81694. this.beforeStep = function () {
  81695. if (!_this._physicsEngine) {
  81696. return;
  81697. }
  81698. _this.object.translate(_this._deltaPosition, -1);
  81699. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81700. _this.object.computeWorldMatrix(false);
  81701. if (_this.object.parent && _this.object.rotationQuaternion) {
  81702. _this.getParentsRotation();
  81703. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81704. }
  81705. else {
  81706. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81707. }
  81708. if (!_this._options.disableBidirectionalTransformation) {
  81709. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81710. }
  81711. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81712. func(_this);
  81713. });
  81714. };
  81715. /**
  81716. * this function is executed by the physics engine.
  81717. */
  81718. this.afterStep = function () {
  81719. if (!_this._physicsEngine) {
  81720. return;
  81721. }
  81722. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81723. func(_this);
  81724. });
  81725. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81726. // object has now its world rotation. needs to be converted to local.
  81727. if (_this.object.parent && _this.object.rotationQuaternion) {
  81728. _this.getParentsRotation();
  81729. _this._tmpQuat.conjugateInPlace();
  81730. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81731. }
  81732. // take the position set and make it the absolute position of this object.
  81733. _this.object.setAbsolutePosition(_this.object.position);
  81734. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81735. _this.object.translate(_this._deltaPosition, 1);
  81736. };
  81737. /**
  81738. * Legacy collision detection event support
  81739. */
  81740. this.onCollideEvent = null;
  81741. //event and body object due to cannon's event-based architecture.
  81742. this.onCollide = function (e) {
  81743. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81744. return;
  81745. }
  81746. if (!_this._physicsEngine) {
  81747. return;
  81748. }
  81749. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81750. if (otherImpostor) {
  81751. // Legacy collision detection event support
  81752. if (_this.onCollideEvent) {
  81753. _this.onCollideEvent(_this, otherImpostor);
  81754. }
  81755. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81756. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81757. }).forEach(function (obj) {
  81758. obj.callback(_this, otherImpostor);
  81759. });
  81760. }
  81761. };
  81762. //sanity check!
  81763. if (!this.object) {
  81764. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81765. return;
  81766. }
  81767. //legacy support for old syntax.
  81768. if (!this._scene && object.getScene) {
  81769. this._scene = object.getScene();
  81770. }
  81771. if (!this._scene) {
  81772. return;
  81773. }
  81774. this._physicsEngine = this._scene.getPhysicsEngine();
  81775. if (!this._physicsEngine) {
  81776. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81777. }
  81778. else {
  81779. //set the object's quaternion, if not set
  81780. if (!this.object.rotationQuaternion) {
  81781. if (this.object.rotation) {
  81782. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81783. }
  81784. else {
  81785. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81786. }
  81787. }
  81788. //default options params
  81789. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81790. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81791. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81792. this._joints = [];
  81793. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81794. if (!this.object.parent || this._options.ignoreParent) {
  81795. this._init();
  81796. }
  81797. else if (this.object.parent.physicsImpostor) {
  81798. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81799. }
  81800. }
  81801. }
  81802. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81803. get: function () {
  81804. return this._isDisposed;
  81805. },
  81806. enumerable: true,
  81807. configurable: true
  81808. });
  81809. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81810. get: function () {
  81811. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81812. },
  81813. set: function (value) {
  81814. this.setMass(value);
  81815. },
  81816. enumerable: true,
  81817. configurable: true
  81818. });
  81819. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81820. get: function () {
  81821. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81822. },
  81823. set: function (value) {
  81824. if (!this._physicsEngine) {
  81825. return;
  81826. }
  81827. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81828. },
  81829. enumerable: true,
  81830. configurable: true
  81831. });
  81832. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81833. get: function () {
  81834. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81835. },
  81836. set: function (value) {
  81837. if (!this._physicsEngine) {
  81838. return;
  81839. }
  81840. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81841. },
  81842. enumerable: true,
  81843. configurable: true
  81844. });
  81845. /**
  81846. * This function will completly initialize this impostor.
  81847. * It will create a new body - but only if this mesh has no parent.
  81848. * If it has, this impostor will not be used other than to define the impostor
  81849. * of the child mesh.
  81850. */
  81851. PhysicsImpostor.prototype._init = function () {
  81852. if (!this._physicsEngine) {
  81853. return;
  81854. }
  81855. this._physicsEngine.removeImpostor(this);
  81856. this.physicsBody = null;
  81857. this._parent = this._parent || this._getPhysicsParent();
  81858. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81859. this._physicsEngine.addImpostor(this);
  81860. }
  81861. };
  81862. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81863. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81864. var parentMesh = this.object.parent;
  81865. return parentMesh.physicsImpostor;
  81866. }
  81867. return null;
  81868. };
  81869. /**
  81870. * Should a new body be generated.
  81871. */
  81872. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81873. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81874. };
  81875. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81876. this.forceUpdate();
  81877. };
  81878. /**
  81879. * Force a regeneration of this or the parent's impostor's body.
  81880. * Use under cautious - This will remove all joints already implemented.
  81881. */
  81882. PhysicsImpostor.prototype.forceUpdate = function () {
  81883. this._init();
  81884. if (this.parent && !this._options.ignoreParent) {
  81885. this.parent.forceUpdate();
  81886. }
  81887. };
  81888. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81889. /*public get mesh(): AbstractMesh {
  81890. return this._mesh;
  81891. }*/
  81892. /**
  81893. * Gets the body that holds this impostor. Either its own, or its parent.
  81894. */
  81895. get: function () {
  81896. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81897. },
  81898. /**
  81899. * Set the physics body. Used mainly by the physics engine/plugin
  81900. */
  81901. set: function (physicsBody) {
  81902. if (this._physicsBody && this._physicsEngine) {
  81903. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81904. }
  81905. this._physicsBody = physicsBody;
  81906. this.resetUpdateFlags();
  81907. },
  81908. enumerable: true,
  81909. configurable: true
  81910. });
  81911. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81912. get: function () {
  81913. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81914. },
  81915. set: function (value) {
  81916. this._parent = value;
  81917. },
  81918. enumerable: true,
  81919. configurable: true
  81920. });
  81921. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81922. this._bodyUpdateRequired = false;
  81923. };
  81924. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81925. if (this.object.getBoundingInfo) {
  81926. var q = this.object.rotationQuaternion;
  81927. //reset rotation
  81928. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81929. //calculate the world matrix with no rotation
  81930. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81931. var boundingInfo = this.object.getBoundingInfo();
  81932. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81933. //bring back the rotation
  81934. this.object.rotationQuaternion = q;
  81935. //calculate the world matrix with the new rotation
  81936. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81937. return size;
  81938. }
  81939. else {
  81940. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81941. }
  81942. };
  81943. PhysicsImpostor.prototype.getObjectCenter = function () {
  81944. if (this.object.getBoundingInfo) {
  81945. var boundingInfo = this.object.getBoundingInfo();
  81946. return boundingInfo.boundingBox.centerWorld;
  81947. }
  81948. else {
  81949. return this.object.position;
  81950. }
  81951. };
  81952. /**
  81953. * Get a specific parametes from the options parameter.
  81954. */
  81955. PhysicsImpostor.prototype.getParam = function (paramName) {
  81956. return this._options[paramName];
  81957. };
  81958. /**
  81959. * Sets a specific parameter in the options given to the physics plugin
  81960. */
  81961. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81962. this._options[paramName] = value;
  81963. this._bodyUpdateRequired = true;
  81964. };
  81965. /**
  81966. * Specifically change the body's mass option. Won't recreate the physics body object
  81967. */
  81968. PhysicsImpostor.prototype.setMass = function (mass) {
  81969. if (this.getParam("mass") !== mass) {
  81970. this.setParam("mass", mass);
  81971. }
  81972. if (this._physicsEngine) {
  81973. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81974. }
  81975. };
  81976. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81977. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81978. };
  81979. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81980. if (this._physicsEngine) {
  81981. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81982. }
  81983. };
  81984. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81985. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81986. };
  81987. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81988. if (this._physicsEngine) {
  81989. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81990. }
  81991. };
  81992. /**
  81993. * Execute a function with the physics plugin native code.
  81994. * Provide a function the will have two variables - the world object and the physics body object.
  81995. */
  81996. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81997. if (this._physicsEngine) {
  81998. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81999. }
  82000. };
  82001. /**
  82002. * Register a function that will be executed before the physics world is stepping forward.
  82003. */
  82004. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82005. this._onBeforePhysicsStepCallbacks.push(func);
  82006. };
  82007. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82008. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82009. if (index > -1) {
  82010. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82011. }
  82012. else {
  82013. BABYLON.Tools.Warn("Function to remove was not found");
  82014. }
  82015. };
  82016. /**
  82017. * Register a function that will be executed after the physics step
  82018. */
  82019. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82020. this._onAfterPhysicsStepCallbacks.push(func);
  82021. };
  82022. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82023. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82024. if (index > -1) {
  82025. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82026. }
  82027. else {
  82028. BABYLON.Tools.Warn("Function to remove was not found");
  82029. }
  82030. };
  82031. /**
  82032. * register a function that will be executed when this impostor collides against a different body.
  82033. */
  82034. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82035. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82036. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82037. };
  82038. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82039. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82040. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82041. if (index > -1) {
  82042. this._onPhysicsCollideCallbacks.splice(index, 1);
  82043. }
  82044. else {
  82045. BABYLON.Tools.Warn("Function to remove was not found");
  82046. }
  82047. };
  82048. PhysicsImpostor.prototype.getParentsRotation = function () {
  82049. var parent = this.object.parent;
  82050. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82051. while (parent) {
  82052. if (parent.rotationQuaternion) {
  82053. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82054. }
  82055. else {
  82056. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82057. }
  82058. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82059. parent = parent.parent;
  82060. }
  82061. return this._tmpQuat;
  82062. };
  82063. /**
  82064. * Apply a force
  82065. */
  82066. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82067. if (this._physicsEngine) {
  82068. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82069. }
  82070. return this;
  82071. };
  82072. /**
  82073. * Apply an impulse
  82074. */
  82075. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82076. if (this._physicsEngine) {
  82077. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82078. }
  82079. return this;
  82080. };
  82081. /**
  82082. * A help function to create a joint.
  82083. */
  82084. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82085. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82086. this.addJoint(otherImpostor, joint);
  82087. return this;
  82088. };
  82089. /**
  82090. * Add a joint to this impostor with a different impostor.
  82091. */
  82092. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82093. this._joints.push({
  82094. otherImpostor: otherImpostor,
  82095. joint: joint
  82096. });
  82097. if (this._physicsEngine) {
  82098. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82099. }
  82100. return this;
  82101. };
  82102. /**
  82103. * Will keep this body still, in a sleep mode.
  82104. */
  82105. PhysicsImpostor.prototype.sleep = function () {
  82106. if (this._physicsEngine) {
  82107. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82108. }
  82109. return this;
  82110. };
  82111. /**
  82112. * Wake the body up.
  82113. */
  82114. PhysicsImpostor.prototype.wakeUp = function () {
  82115. if (this._physicsEngine) {
  82116. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82117. }
  82118. return this;
  82119. };
  82120. PhysicsImpostor.prototype.clone = function (newObject) {
  82121. if (!newObject)
  82122. return null;
  82123. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82124. };
  82125. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82126. var _this = this;
  82127. //no dispose if no physics engine is available.
  82128. if (!this._physicsEngine) {
  82129. return;
  82130. }
  82131. this._joints.forEach(function (j) {
  82132. if (_this._physicsEngine) {
  82133. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82134. }
  82135. });
  82136. //dispose the physics body
  82137. this._physicsEngine.removeImpostor(this);
  82138. if (this.parent) {
  82139. this.parent.forceUpdate();
  82140. }
  82141. else {
  82142. /*this._object.getChildMeshes().forEach(function(mesh) {
  82143. if (mesh.physicsImpostor) {
  82144. if (disposeChildren) {
  82145. mesh.physicsImpostor.dispose();
  82146. mesh.physicsImpostor = null;
  82147. }
  82148. }
  82149. })*/
  82150. }
  82151. this._isDisposed = true;
  82152. };
  82153. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82154. this._deltaPosition.copyFrom(position);
  82155. };
  82156. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82157. if (!this._deltaRotation) {
  82158. this._deltaRotation = new BABYLON.Quaternion();
  82159. }
  82160. this._deltaRotation.copyFrom(rotation);
  82161. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82162. };
  82163. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82164. if (this._physicsEngine) {
  82165. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82166. }
  82167. return this;
  82168. };
  82169. PhysicsImpostor.prototype.getRadius = function () {
  82170. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82171. };
  82172. /**
  82173. * Sync a bone with this impostor
  82174. * @param bone The bone to sync to the impostor.
  82175. * @param boneMesh The mesh that the bone is influencing.
  82176. * @param jointPivot The pivot of the joint / bone in local space.
  82177. * @param distToJoint Optional distance from the impostor to the joint.
  82178. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82179. */
  82180. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82181. var tempVec = PhysicsImpostor._tmpVecs[0];
  82182. var mesh = this.object;
  82183. if (mesh.rotationQuaternion) {
  82184. if (adjustRotation) {
  82185. var tempQuat = PhysicsImpostor._tmpQuat;
  82186. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82187. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82188. }
  82189. else {
  82190. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82191. }
  82192. }
  82193. tempVec.x = 0;
  82194. tempVec.y = 0;
  82195. tempVec.z = 0;
  82196. if (jointPivot) {
  82197. tempVec.x = jointPivot.x;
  82198. tempVec.y = jointPivot.y;
  82199. tempVec.z = jointPivot.z;
  82200. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82201. if (distToJoint === undefined || distToJoint === null) {
  82202. distToJoint = jointPivot.length();
  82203. }
  82204. tempVec.x *= distToJoint;
  82205. tempVec.y *= distToJoint;
  82206. tempVec.z *= distToJoint;
  82207. }
  82208. if (bone.getParent()) {
  82209. tempVec.addInPlace(mesh.getAbsolutePosition());
  82210. bone.setAbsolutePosition(tempVec, boneMesh);
  82211. }
  82212. else {
  82213. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82214. boneMesh.position.x -= tempVec.x;
  82215. boneMesh.position.y -= tempVec.y;
  82216. boneMesh.position.z -= tempVec.z;
  82217. }
  82218. };
  82219. /**
  82220. * Sync impostor to a bone
  82221. * @param bone The bone that the impostor will be synced to.
  82222. * @param boneMesh The mesh that the bone is influencing.
  82223. * @param jointPivot The pivot of the joint / bone in local space.
  82224. * @param distToJoint Optional distance from the impostor to the joint.
  82225. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82226. * @param boneAxis Optional vector3 axis the bone is aligned with
  82227. */
  82228. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82229. var mesh = this.object;
  82230. if (mesh.rotationQuaternion) {
  82231. if (adjustRotation) {
  82232. var tempQuat = PhysicsImpostor._tmpQuat;
  82233. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82234. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82235. }
  82236. else {
  82237. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82238. }
  82239. }
  82240. var pos = PhysicsImpostor._tmpVecs[0];
  82241. var boneDir = PhysicsImpostor._tmpVecs[1];
  82242. if (!boneAxis) {
  82243. boneAxis = PhysicsImpostor._tmpVecs[2];
  82244. boneAxis.x = 0;
  82245. boneAxis.y = 1;
  82246. boneAxis.z = 0;
  82247. }
  82248. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82249. bone.getAbsolutePositionToRef(boneMesh, pos);
  82250. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82251. distToJoint = jointPivot.length();
  82252. }
  82253. if (distToJoint !== undefined && distToJoint !== null) {
  82254. pos.x += boneDir.x * distToJoint;
  82255. pos.y += boneDir.y * distToJoint;
  82256. pos.z += boneDir.z * distToJoint;
  82257. }
  82258. mesh.setAbsolutePosition(pos);
  82259. };
  82260. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82261. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82262. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82263. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82264. //Impostor types
  82265. PhysicsImpostor.NoImpostor = 0;
  82266. PhysicsImpostor.SphereImpostor = 1;
  82267. PhysicsImpostor.BoxImpostor = 2;
  82268. PhysicsImpostor.PlaneImpostor = 3;
  82269. PhysicsImpostor.MeshImpostor = 4;
  82270. PhysicsImpostor.CylinderImpostor = 7;
  82271. PhysicsImpostor.ParticleImpostor = 8;
  82272. PhysicsImpostor.HeightmapImpostor = 9;
  82273. return PhysicsImpostor;
  82274. }());
  82275. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82276. })(BABYLON || (BABYLON = {}));
  82277. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82278. var BABYLON;
  82279. (function (BABYLON) {
  82280. var PhysicsEngine = /** @class */ (function () {
  82281. function PhysicsEngine(gravity, _physicsPlugin) {
  82282. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82283. this._physicsPlugin = _physicsPlugin;
  82284. //new methods and parameters
  82285. this._impostors = [];
  82286. this._joints = [];
  82287. if (!this._physicsPlugin.isSupported()) {
  82288. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82289. + "Please make sure it is included.");
  82290. }
  82291. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82292. this.setGravity(gravity);
  82293. this.setTimeStep();
  82294. }
  82295. PhysicsEngine.prototype.setGravity = function (gravity) {
  82296. this.gravity = gravity;
  82297. this._physicsPlugin.setGravity(this.gravity);
  82298. };
  82299. /**
  82300. * Set the time step of the physics engine.
  82301. * default is 1/60.
  82302. * To slow it down, enter 1/600 for example.
  82303. * To speed it up, 1/30
  82304. * @param {number} newTimeStep the new timestep to apply to this world.
  82305. */
  82306. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82307. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82308. this._physicsPlugin.setTimeStep(newTimeStep);
  82309. };
  82310. /**
  82311. * Get the time step of the physics engine.
  82312. */
  82313. PhysicsEngine.prototype.getTimeStep = function () {
  82314. return this._physicsPlugin.getTimeStep();
  82315. };
  82316. PhysicsEngine.prototype.dispose = function () {
  82317. this._impostors.forEach(function (impostor) {
  82318. impostor.dispose();
  82319. });
  82320. this._physicsPlugin.dispose();
  82321. };
  82322. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82323. return this._physicsPlugin.name;
  82324. };
  82325. /**
  82326. * Adding a new impostor for the impostor tracking.
  82327. * This will be done by the impostor itself.
  82328. * @param {PhysicsImpostor} impostor the impostor to add
  82329. */
  82330. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82331. impostor.uniqueId = this._impostors.push(impostor);
  82332. //if no parent, generate the body
  82333. if (!impostor.parent) {
  82334. this._physicsPlugin.generatePhysicsBody(impostor);
  82335. }
  82336. };
  82337. /**
  82338. * Remove an impostor from the engine.
  82339. * This impostor and its mesh will not longer be updated by the physics engine.
  82340. * @param {PhysicsImpostor} impostor the impostor to remove
  82341. */
  82342. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82343. var index = this._impostors.indexOf(impostor);
  82344. if (index > -1) {
  82345. var removed = this._impostors.splice(index, 1);
  82346. //Is it needed?
  82347. if (removed.length) {
  82348. //this will also remove it from the world.
  82349. removed[0].physicsBody = null;
  82350. }
  82351. }
  82352. };
  82353. /**
  82354. * Add a joint to the physics engine
  82355. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82356. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82357. * @param {PhysicsJoint} the joint that will connect both impostors.
  82358. */
  82359. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82360. var impostorJoint = {
  82361. mainImpostor: mainImpostor,
  82362. connectedImpostor: connectedImpostor,
  82363. joint: joint
  82364. };
  82365. joint.physicsPlugin = this._physicsPlugin;
  82366. this._joints.push(impostorJoint);
  82367. this._physicsPlugin.generateJoint(impostorJoint);
  82368. };
  82369. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82370. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82371. return (impostorJoint.connectedImpostor === connectedImpostor
  82372. && impostorJoint.joint === joint
  82373. && impostorJoint.mainImpostor === mainImpostor);
  82374. });
  82375. if (matchingJoints.length) {
  82376. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82377. //TODO remove it from the list as well
  82378. }
  82379. };
  82380. /**
  82381. * Called by the scene. no need to call it.
  82382. */
  82383. PhysicsEngine.prototype._step = function (delta) {
  82384. var _this = this;
  82385. //check if any mesh has no body / requires an update
  82386. this._impostors.forEach(function (impostor) {
  82387. if (impostor.isBodyInitRequired()) {
  82388. _this._physicsPlugin.generatePhysicsBody(impostor);
  82389. }
  82390. });
  82391. if (delta > 0.1) {
  82392. delta = 0.1;
  82393. }
  82394. else if (delta <= 0) {
  82395. delta = 1.0 / 60.0;
  82396. }
  82397. this._physicsPlugin.executeStep(delta, this._impostors);
  82398. };
  82399. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82400. return this._physicsPlugin;
  82401. };
  82402. PhysicsEngine.prototype.getImpostors = function () {
  82403. return this._impostors;
  82404. };
  82405. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82406. for (var i = 0; i < this._impostors.length; ++i) {
  82407. if (this._impostors[i].object === object) {
  82408. return this._impostors[i];
  82409. }
  82410. }
  82411. return null;
  82412. };
  82413. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82414. for (var i = 0; i < this._impostors.length; ++i) {
  82415. if (this._impostors[i].physicsBody === body) {
  82416. return this._impostors[i];
  82417. }
  82418. }
  82419. return null;
  82420. };
  82421. // Statics
  82422. PhysicsEngine.Epsilon = 0.001;
  82423. return PhysicsEngine;
  82424. }());
  82425. BABYLON.PhysicsEngine = PhysicsEngine;
  82426. })(BABYLON || (BABYLON = {}));
  82427. //# sourceMappingURL=babylon.physicsEngine.js.map
  82428. var BABYLON;
  82429. (function (BABYLON) {
  82430. var PhysicsHelper = /** @class */ (function () {
  82431. function PhysicsHelper(scene) {
  82432. this._scene = scene;
  82433. this._physicsEngine = this._scene.getPhysicsEngine();
  82434. if (!this._physicsEngine) {
  82435. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82436. }
  82437. }
  82438. /**
  82439. * @param {Vector3} origin the origin of the explosion
  82440. * @param {number} radius the explosion radius
  82441. * @param {number} strength the explosion strength
  82442. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82443. */
  82444. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82445. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82446. if (!this._physicsEngine) {
  82447. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82448. return null;
  82449. }
  82450. var impostors = this._physicsEngine.getImpostors();
  82451. if (impostors.length === 0) {
  82452. return null;
  82453. }
  82454. var event = new PhysicsRadialExplosionEvent(this._scene);
  82455. impostors.forEach(function (impostor) {
  82456. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82457. if (!impostorForceAndContactPoint) {
  82458. return;
  82459. }
  82460. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82461. });
  82462. event.dispose(false);
  82463. return event;
  82464. };
  82465. /**
  82466. * @param {Vector3} origin the origin of the explosion
  82467. * @param {number} radius the explosion radius
  82468. * @param {number} strength the explosion strength
  82469. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82470. */
  82471. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82472. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82473. if (!this._physicsEngine) {
  82474. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82475. return null;
  82476. }
  82477. var impostors = this._physicsEngine.getImpostors();
  82478. if (impostors.length === 0) {
  82479. return null;
  82480. }
  82481. var event = new PhysicsRadialExplosionEvent(this._scene);
  82482. impostors.forEach(function (impostor) {
  82483. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82484. if (!impostorForceAndContactPoint) {
  82485. return;
  82486. }
  82487. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82488. });
  82489. event.dispose(false);
  82490. return event;
  82491. };
  82492. /**
  82493. * @param {Vector3} origin the origin of the explosion
  82494. * @param {number} radius the explosion radius
  82495. * @param {number} strength the explosion strength
  82496. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82497. */
  82498. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82499. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82500. if (!this._physicsEngine) {
  82501. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82502. return null;
  82503. }
  82504. var impostors = this._physicsEngine.getImpostors();
  82505. if (impostors.length === 0) {
  82506. return null;
  82507. }
  82508. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82509. event.dispose(false);
  82510. return event;
  82511. };
  82512. /**
  82513. * @param {Vector3} origin the origin of the updraft
  82514. * @param {number} radius the radius of the updraft
  82515. * @param {number} strength the strength of the updraft
  82516. * @param {number} height the height of the updraft
  82517. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82518. */
  82519. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82520. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82521. if (!this._physicsEngine) {
  82522. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82523. return null;
  82524. }
  82525. if (this._physicsEngine.getImpostors().length === 0) {
  82526. return null;
  82527. }
  82528. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82529. event.dispose(false);
  82530. return event;
  82531. };
  82532. /**
  82533. * @param {Vector3} origin the of the vortex
  82534. * @param {number} radius the radius of the vortex
  82535. * @param {number} strength the strength of the vortex
  82536. * @param {number} height the height of the vortex
  82537. */
  82538. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82539. if (!this._physicsEngine) {
  82540. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82541. return null;
  82542. }
  82543. if (this._physicsEngine.getImpostors().length === 0) {
  82544. return null;
  82545. }
  82546. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82547. event.dispose(false);
  82548. return event;
  82549. };
  82550. return PhysicsHelper;
  82551. }());
  82552. BABYLON.PhysicsHelper = PhysicsHelper;
  82553. /***** Radial explosion *****/
  82554. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82555. function PhysicsRadialExplosionEvent(scene) {
  82556. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82557. this._rays = [];
  82558. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82559. this._scene = scene;
  82560. }
  82561. /**
  82562. * Returns the data related to the radial explosion event (sphere & rays).
  82563. * @returns {PhysicsRadialExplosionEventData}
  82564. */
  82565. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82566. this._dataFetched = true;
  82567. return {
  82568. sphere: this._sphere,
  82569. rays: this._rays,
  82570. };
  82571. };
  82572. /**
  82573. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82574. * @param impostor
  82575. * @param {Vector3} origin the origin of the explosion
  82576. * @param {number} radius the explosion radius
  82577. * @param {number} strength the explosion strength
  82578. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82579. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82580. */
  82581. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82582. if (impostor.mass === 0) {
  82583. return null;
  82584. }
  82585. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82586. return null;
  82587. }
  82588. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82589. return null;
  82590. }
  82591. var impostorObjectCenter = impostor.getObjectCenter();
  82592. var direction = impostorObjectCenter.subtract(origin);
  82593. var ray = new BABYLON.Ray(origin, direction, radius);
  82594. this._rays.push(ray);
  82595. var hit = ray.intersectsMesh(impostor.object);
  82596. var contactPoint = hit.pickedPoint;
  82597. if (!contactPoint) {
  82598. return null;
  82599. }
  82600. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82601. if (distanceFromOrigin > radius) {
  82602. return null;
  82603. }
  82604. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82605. ? strength
  82606. : strength * (1 - (distanceFromOrigin / radius));
  82607. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82608. return { force: force, contactPoint: contactPoint };
  82609. };
  82610. /**
  82611. * Disposes the sphere.
  82612. * @param {bolean} force
  82613. */
  82614. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82615. var _this = this;
  82616. if (force === void 0) { force = true; }
  82617. if (force) {
  82618. this._sphere.dispose();
  82619. }
  82620. else {
  82621. setTimeout(function () {
  82622. if (!_this._dataFetched) {
  82623. _this._sphere.dispose();
  82624. }
  82625. }, 0);
  82626. }
  82627. };
  82628. /*** Helpers ***/
  82629. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82630. if (!this._sphere) {
  82631. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82632. this._sphere.isVisible = false;
  82633. }
  82634. };
  82635. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82636. var impostorObject = impostor.object;
  82637. this._prepareSphere();
  82638. this._sphere.position = origin;
  82639. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82640. this._sphere._updateBoundingInfo();
  82641. this._sphere.computeWorldMatrix(true);
  82642. return this._sphere.intersectsMesh(impostorObject, true);
  82643. };
  82644. return PhysicsRadialExplosionEvent;
  82645. }());
  82646. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82647. /***** Gravitational Field *****/
  82648. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82649. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82650. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82651. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82652. this._physicsHelper = physicsHelper;
  82653. this._scene = scene;
  82654. this._origin = origin;
  82655. this._radius = radius;
  82656. this._strength = strength;
  82657. this._falloff = falloff;
  82658. this._tickCallback = this._tick.bind(this);
  82659. }
  82660. /**
  82661. * Returns the data related to the gravitational field event (sphere).
  82662. * @returns {PhysicsGravitationalFieldEventData}
  82663. */
  82664. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82665. this._dataFetched = true;
  82666. return {
  82667. sphere: this._sphere,
  82668. };
  82669. };
  82670. /**
  82671. * Enables the gravitational field.
  82672. */
  82673. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82674. this._tickCallback.call(this);
  82675. this._scene.registerBeforeRender(this._tickCallback);
  82676. };
  82677. /**
  82678. * Disables the gravitational field.
  82679. */
  82680. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82681. this._scene.unregisterBeforeRender(this._tickCallback);
  82682. };
  82683. /**
  82684. * Disposes the sphere.
  82685. * @param {bolean} force
  82686. */
  82687. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82688. var _this = this;
  82689. if (force === void 0) { force = true; }
  82690. if (force) {
  82691. this._sphere.dispose();
  82692. }
  82693. else {
  82694. setTimeout(function () {
  82695. if (!_this._dataFetched) {
  82696. _this._sphere.dispose();
  82697. }
  82698. }, 0);
  82699. }
  82700. };
  82701. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82702. // Since the params won't change, we fetch the event only once
  82703. if (this._sphere) {
  82704. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82705. }
  82706. else {
  82707. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82708. if (radialExplosionEvent) {
  82709. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82710. }
  82711. }
  82712. };
  82713. return PhysicsGravitationalFieldEvent;
  82714. }());
  82715. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82716. /***** Updraft *****/
  82717. var PhysicsUpdraftEvent = /** @class */ (function () {
  82718. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82719. this._scene = _scene;
  82720. this._origin = _origin;
  82721. this._radius = _radius;
  82722. this._strength = _strength;
  82723. this._height = _height;
  82724. this._updraftMode = _updraftMode;
  82725. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82726. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82727. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82728. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82729. this._physicsEngine = this._scene.getPhysicsEngine();
  82730. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82731. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82732. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82733. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82734. }
  82735. this._tickCallback = this._tick.bind(this);
  82736. }
  82737. /**
  82738. * Returns the data related to the updraft event (cylinder).
  82739. * @returns {PhysicsUpdraftEventData}
  82740. */
  82741. PhysicsUpdraftEvent.prototype.getData = function () {
  82742. this._dataFetched = true;
  82743. return {
  82744. cylinder: this._cylinder,
  82745. };
  82746. };
  82747. /**
  82748. * Enables the updraft.
  82749. */
  82750. PhysicsUpdraftEvent.prototype.enable = function () {
  82751. this._tickCallback.call(this);
  82752. this._scene.registerBeforeRender(this._tickCallback);
  82753. };
  82754. /**
  82755. * Disables the cortex.
  82756. */
  82757. PhysicsUpdraftEvent.prototype.disable = function () {
  82758. this._scene.unregisterBeforeRender(this._tickCallback);
  82759. };
  82760. /**
  82761. * Disposes the sphere.
  82762. * @param {bolean} force
  82763. */
  82764. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82765. var _this = this;
  82766. if (force === void 0) { force = true; }
  82767. if (force) {
  82768. this._cylinder.dispose();
  82769. }
  82770. else {
  82771. setTimeout(function () {
  82772. if (!_this._dataFetched) {
  82773. _this._cylinder.dispose();
  82774. }
  82775. }, 0);
  82776. }
  82777. };
  82778. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82779. if (impostor.mass === 0) {
  82780. return null;
  82781. }
  82782. if (!this._intersectsWithCylinder(impostor)) {
  82783. return null;
  82784. }
  82785. var impostorObjectCenter = impostor.getObjectCenter();
  82786. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82787. var direction = this._originDirection;
  82788. }
  82789. else {
  82790. var direction = impostorObjectCenter.subtract(this._originTop);
  82791. }
  82792. var multiplier = this._strength * -1;
  82793. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82794. return { force: force, contactPoint: impostorObjectCenter };
  82795. };
  82796. PhysicsUpdraftEvent.prototype._tick = function () {
  82797. var _this = this;
  82798. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82799. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82800. if (!impostorForceAndContactPoint) {
  82801. return;
  82802. }
  82803. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82804. });
  82805. };
  82806. /*** Helpers ***/
  82807. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82808. if (!this._cylinder) {
  82809. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82810. height: this._height,
  82811. diameter: this._radius * 2,
  82812. }, this._scene);
  82813. this._cylinder.isVisible = false;
  82814. }
  82815. };
  82816. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82817. var impostorObject = impostor.object;
  82818. this._prepareCylinder();
  82819. this._cylinder.position = this._cylinderPosition;
  82820. return this._cylinder.intersectsMesh(impostorObject, true);
  82821. };
  82822. return PhysicsUpdraftEvent;
  82823. }());
  82824. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82825. /***** Vortex *****/
  82826. var PhysicsVortexEvent = /** @class */ (function () {
  82827. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82828. this._scene = _scene;
  82829. this._origin = _origin;
  82830. this._radius = _radius;
  82831. this._strength = _strength;
  82832. this._height = _height;
  82833. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82834. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82835. this._updraftMultiplier = 0.02;
  82836. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82837. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82838. this._physicsEngine = this._scene.getPhysicsEngine();
  82839. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82840. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82841. this._tickCallback = this._tick.bind(this);
  82842. }
  82843. /**
  82844. * Returns the data related to the vortex event (cylinder).
  82845. * @returns {PhysicsVortexEventData}
  82846. */
  82847. PhysicsVortexEvent.prototype.getData = function () {
  82848. this._dataFetched = true;
  82849. return {
  82850. cylinder: this._cylinder,
  82851. };
  82852. };
  82853. /**
  82854. * Enables the vortex.
  82855. */
  82856. PhysicsVortexEvent.prototype.enable = function () {
  82857. this._tickCallback.call(this);
  82858. this._scene.registerBeforeRender(this._tickCallback);
  82859. };
  82860. /**
  82861. * Disables the cortex.
  82862. */
  82863. PhysicsVortexEvent.prototype.disable = function () {
  82864. this._scene.unregisterBeforeRender(this._tickCallback);
  82865. };
  82866. /**
  82867. * Disposes the sphere.
  82868. * @param {bolean} force
  82869. */
  82870. PhysicsVortexEvent.prototype.dispose = function (force) {
  82871. var _this = this;
  82872. if (force === void 0) { force = true; }
  82873. if (force) {
  82874. this._cylinder.dispose();
  82875. }
  82876. else {
  82877. setTimeout(function () {
  82878. if (!_this._dataFetched) {
  82879. _this._cylinder.dispose();
  82880. }
  82881. }, 0);
  82882. }
  82883. };
  82884. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82885. if (impostor.mass === 0) {
  82886. return null;
  82887. }
  82888. if (!this._intersectsWithCylinder(impostor)) {
  82889. return null;
  82890. }
  82891. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82892. return null;
  82893. }
  82894. var impostorObjectCenter = impostor.getObjectCenter();
  82895. 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)
  82896. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82897. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82898. var hit = ray.intersectsMesh(impostor.object);
  82899. var contactPoint = hit.pickedPoint;
  82900. if (!contactPoint) {
  82901. return null;
  82902. }
  82903. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82904. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82905. var directionToOrigin = contactPoint.normalize();
  82906. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82907. directionToOrigin = directionToOrigin.negate();
  82908. }
  82909. // TODO: find a more physically based solution
  82910. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82911. var forceX = directionToOrigin.x * this._strength / 8;
  82912. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82913. var forceZ = directionToOrigin.z * this._strength / 8;
  82914. }
  82915. else {
  82916. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82917. var forceY = this._originTop.y * this._updraftMultiplier;
  82918. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82919. }
  82920. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82921. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82922. return { force: force, contactPoint: impostorObjectCenter };
  82923. };
  82924. PhysicsVortexEvent.prototype._tick = function () {
  82925. var _this = this;
  82926. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82927. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82928. if (!impostorForceAndContactPoint) {
  82929. return;
  82930. }
  82931. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82932. });
  82933. };
  82934. /*** Helpers ***/
  82935. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82936. if (!this._cylinder) {
  82937. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82938. height: this._height,
  82939. diameter: this._radius * 2,
  82940. }, this._scene);
  82941. this._cylinder.isVisible = false;
  82942. }
  82943. };
  82944. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82945. var impostorObject = impostor.object;
  82946. this._prepareCylinder();
  82947. this._cylinder.position = this._cylinderPosition;
  82948. return this._cylinder.intersectsMesh(impostorObject, true);
  82949. };
  82950. return PhysicsVortexEvent;
  82951. }());
  82952. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82953. /***** Enums *****/
  82954. /**
  82955. * The strenght of the force in correspondence to the distance of the affected object
  82956. */
  82957. var PhysicsRadialImpulseFalloff;
  82958. (function (PhysicsRadialImpulseFalloff) {
  82959. /** Defines that impulse is constant in strength across it's whole radius */
  82960. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82961. /** DEfines that impulse gets weaker if it's further from the origin */
  82962. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82963. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82964. /**
  82965. * The strenght of the force in correspondence to the distance of the affected object
  82966. */
  82967. var PhysicsUpdraftMode;
  82968. (function (PhysicsUpdraftMode) {
  82969. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82970. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82971. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82972. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82973. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82974. })(BABYLON || (BABYLON = {}));
  82975. //# sourceMappingURL=babylon.physicsHelper.js.map
  82976. var BABYLON;
  82977. (function (BABYLON) {
  82978. var CannonJSPlugin = /** @class */ (function () {
  82979. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82980. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82981. if (iterations === void 0) { iterations = 10; }
  82982. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82983. this.name = "CannonJSPlugin";
  82984. this._physicsMaterials = new Array();
  82985. this._fixedTimeStep = 1 / 60;
  82986. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82987. this.BJSCANNON = CANNON;
  82988. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82989. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82990. this._tmpPosition = BABYLON.Vector3.Zero();
  82991. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82992. this._tmpUnityRotation = new BABYLON.Quaternion();
  82993. if (!this.isSupported()) {
  82994. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82995. return;
  82996. }
  82997. this._extendNamespace();
  82998. this.world = new this.BJSCANNON.World();
  82999. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83000. this.world.solver.iterations = iterations;
  83001. }
  83002. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83003. this.world.gravity.copy(gravity);
  83004. };
  83005. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83006. this._fixedTimeStep = timeStep;
  83007. };
  83008. CannonJSPlugin.prototype.getTimeStep = function () {
  83009. return this._fixedTimeStep;
  83010. };
  83011. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83012. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83013. };
  83014. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83015. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83016. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83017. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83018. };
  83019. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83020. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83021. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83022. impostor.physicsBody.applyForce(impulse, worldPoint);
  83023. };
  83024. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83025. //parent-child relationship. Does this impostor has a parent impostor?
  83026. if (impostor.parent) {
  83027. if (impostor.physicsBody) {
  83028. this.removePhysicsBody(impostor);
  83029. //TODO is that needed?
  83030. impostor.forceUpdate();
  83031. }
  83032. return;
  83033. }
  83034. //should a new body be created for this impostor?
  83035. if (impostor.isBodyInitRequired()) {
  83036. var shape = this._createShape(impostor);
  83037. //unregister events, if body is being changed
  83038. var oldBody = impostor.physicsBody;
  83039. if (oldBody) {
  83040. this.removePhysicsBody(impostor);
  83041. }
  83042. //create the body and material
  83043. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83044. var bodyCreationObject = {
  83045. mass: impostor.getParam("mass"),
  83046. material: material
  83047. };
  83048. // A simple extend, in case native options were used.
  83049. var nativeOptions = impostor.getParam("nativeOptions");
  83050. for (var key in nativeOptions) {
  83051. if (nativeOptions.hasOwnProperty(key)) {
  83052. bodyCreationObject[key] = nativeOptions[key];
  83053. }
  83054. }
  83055. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83056. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83057. this.world.addEventListener("preStep", impostor.beforeStep);
  83058. this.world.addEventListener("postStep", impostor.afterStep);
  83059. impostor.physicsBody.addShape(shape);
  83060. this.world.add(impostor.physicsBody);
  83061. //try to keep the body moving in the right direction by taking old properties.
  83062. //Should be tested!
  83063. if (oldBody) {
  83064. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83065. impostor.physicsBody[param].copy(oldBody[param]);
  83066. });
  83067. }
  83068. this._processChildMeshes(impostor);
  83069. }
  83070. //now update the body's transformation
  83071. this._updatePhysicsBodyTransformation(impostor);
  83072. };
  83073. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83074. var _this = this;
  83075. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83076. var currentRotation = mainImpostor.object.rotationQuaternion;
  83077. if (meshChildren.length) {
  83078. var processMesh = function (localPosition, mesh) {
  83079. if (!currentRotation || !mesh.rotationQuaternion) {
  83080. return;
  83081. }
  83082. var childImpostor = mesh.getPhysicsImpostor();
  83083. if (childImpostor) {
  83084. var parent = childImpostor.parent;
  83085. if (parent !== mainImpostor) {
  83086. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83087. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83088. if (childImpostor.physicsBody) {
  83089. _this.removePhysicsBody(childImpostor);
  83090. childImpostor.physicsBody = null;
  83091. }
  83092. childImpostor.parent = mainImpostor;
  83093. childImpostor.resetUpdateFlags();
  83094. 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));
  83095. //Add the mass of the children.
  83096. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83097. }
  83098. }
  83099. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83100. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83101. };
  83102. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83103. }
  83104. };
  83105. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83106. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83107. this.world.removeEventListener("preStep", impostor.beforeStep);
  83108. this.world.removeEventListener("postStep", impostor.afterStep);
  83109. this.world.remove(impostor.physicsBody);
  83110. };
  83111. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83112. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83113. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83114. if (!mainBody || !connectedBody) {
  83115. return;
  83116. }
  83117. var constraint;
  83118. var jointData = impostorJoint.joint.jointData;
  83119. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83120. var constraintData = {
  83121. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83122. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83123. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83124. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83125. maxForce: jointData.nativeParams.maxForce,
  83126. collideConnected: !!jointData.collision
  83127. };
  83128. switch (impostorJoint.joint.type) {
  83129. case BABYLON.PhysicsJoint.HingeJoint:
  83130. case BABYLON.PhysicsJoint.Hinge2Joint:
  83131. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83132. break;
  83133. case BABYLON.PhysicsJoint.DistanceJoint:
  83134. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83135. break;
  83136. case BABYLON.PhysicsJoint.SpringJoint:
  83137. var springData = jointData;
  83138. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83139. restLength: springData.length,
  83140. stiffness: springData.stiffness,
  83141. damping: springData.damping,
  83142. localAnchorA: constraintData.pivotA,
  83143. localAnchorB: constraintData.pivotB
  83144. });
  83145. break;
  83146. case BABYLON.PhysicsJoint.LockJoint:
  83147. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83148. break;
  83149. case BABYLON.PhysicsJoint.PointToPointJoint:
  83150. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83151. default:
  83152. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83153. break;
  83154. }
  83155. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83156. constraint.collideConnected = !!jointData.collision;
  83157. impostorJoint.joint.physicsJoint = constraint;
  83158. //don't add spring as constraint, as it is not one.
  83159. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83160. this.world.addConstraint(constraint);
  83161. }
  83162. else {
  83163. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83164. constraint.applyForce();
  83165. });
  83166. }
  83167. };
  83168. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83169. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83170. };
  83171. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83172. var index;
  83173. var mat;
  83174. for (index = 0; index < this._physicsMaterials.length; index++) {
  83175. mat = this._physicsMaterials[index];
  83176. if (mat.friction === friction && mat.restitution === restitution) {
  83177. return mat;
  83178. }
  83179. }
  83180. var currentMat = new this.BJSCANNON.Material(name);
  83181. currentMat.friction = friction;
  83182. currentMat.restitution = restitution;
  83183. this._physicsMaterials.push(currentMat);
  83184. return currentMat;
  83185. };
  83186. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83187. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83188. };
  83189. CannonJSPlugin.prototype._createShape = function (impostor) {
  83190. var object = impostor.object;
  83191. var returnValue;
  83192. var extendSize = impostor.getObjectExtendSize();
  83193. switch (impostor.type) {
  83194. case BABYLON.PhysicsImpostor.SphereImpostor:
  83195. var radiusX = extendSize.x;
  83196. var radiusY = extendSize.y;
  83197. var radiusZ = extendSize.z;
  83198. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83199. break;
  83200. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83201. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83202. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83203. break;
  83204. case BABYLON.PhysicsImpostor.BoxImpostor:
  83205. var box = extendSize.scale(0.5);
  83206. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83207. break;
  83208. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83209. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83210. returnValue = new this.BJSCANNON.Plane();
  83211. break;
  83212. case BABYLON.PhysicsImpostor.MeshImpostor:
  83213. // should transform the vertex data to world coordinates!!
  83214. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83215. var rawFaces = object.getIndices ? object.getIndices() : [];
  83216. if (!rawVerts)
  83217. return;
  83218. // get only scale! so the object could transform correctly.
  83219. var oldPosition = object.position.clone();
  83220. var oldRotation = object.rotation && object.rotation.clone();
  83221. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83222. object.position.copyFromFloats(0, 0, 0);
  83223. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83224. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83225. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83226. var transform = object.computeWorldMatrix(true);
  83227. // convert rawVerts to object space
  83228. var temp = new Array();
  83229. var index;
  83230. for (index = 0; index < rawVerts.length; index += 3) {
  83231. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83232. }
  83233. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83234. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83235. //now set back the transformation!
  83236. object.position.copyFrom(oldPosition);
  83237. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83238. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83239. break;
  83240. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83241. var oldPosition2 = object.position.clone();
  83242. var oldRotation2 = object.rotation && object.rotation.clone();
  83243. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83244. object.position.copyFromFloats(0, 0, 0);
  83245. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83246. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83247. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83248. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83249. returnValue = this._createHeightmap(object);
  83250. object.position.copyFrom(oldPosition2);
  83251. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83252. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83253. object.computeWorldMatrix(true);
  83254. break;
  83255. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83256. returnValue = new this.BJSCANNON.Particle();
  83257. break;
  83258. }
  83259. return returnValue;
  83260. };
  83261. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83262. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83263. var transform = object.computeWorldMatrix(true);
  83264. // convert rawVerts to object space
  83265. var temp = new Array();
  83266. var index;
  83267. for (index = 0; index < pos.length; index += 3) {
  83268. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83269. }
  83270. pos = temp;
  83271. var matrix = new Array();
  83272. //For now pointDepth will not be used and will be automatically calculated.
  83273. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83274. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83275. var boundingInfo = object.getBoundingInfo();
  83276. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83277. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83278. var elementSize = dim * 2 / arraySize;
  83279. for (var i = 0; i < pos.length; i = i + 3) {
  83280. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83281. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83282. var y = -pos[i + 2] + minY;
  83283. if (!matrix[x]) {
  83284. matrix[x] = [];
  83285. }
  83286. if (!matrix[x][z]) {
  83287. matrix[x][z] = y;
  83288. }
  83289. matrix[x][z] = Math.max(y, matrix[x][z]);
  83290. }
  83291. for (var x = 0; x <= arraySize; ++x) {
  83292. if (!matrix[x]) {
  83293. var loc = 1;
  83294. while (!matrix[(x + loc) % arraySize]) {
  83295. loc++;
  83296. }
  83297. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83298. //console.log("missing x", x);
  83299. }
  83300. for (var z = 0; z <= arraySize; ++z) {
  83301. if (!matrix[x][z]) {
  83302. var loc = 1;
  83303. var newValue;
  83304. while (newValue === undefined) {
  83305. newValue = matrix[x][(z + loc++) % arraySize];
  83306. }
  83307. matrix[x][z] = newValue;
  83308. }
  83309. }
  83310. }
  83311. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83312. elementSize: elementSize
  83313. });
  83314. //For future reference, needed for body transformation
  83315. shape.minY = minY;
  83316. return shape;
  83317. };
  83318. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83319. var object = impostor.object;
  83320. //make sure it is updated...
  83321. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83322. // The delta between the mesh position and the mesh bounding box center
  83323. var bInfo = object.getBoundingInfo();
  83324. if (!bInfo)
  83325. return;
  83326. var center = impostor.getObjectCenter();
  83327. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83328. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83329. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83330. this._tmpPosition.copyFrom(center);
  83331. var quaternion = object.rotationQuaternion;
  83332. if (!quaternion) {
  83333. return;
  83334. }
  83335. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83336. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83337. //-90 DEG in X, precalculated
  83338. quaternion = quaternion.multiply(this._minus90X);
  83339. //Invert! (Precalculated, 90 deg in X)
  83340. //No need to clone. this will never change.
  83341. impostor.setDeltaRotation(this._plus90X);
  83342. }
  83343. //If it is a heightfield, if should be centered.
  83344. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83345. var mesh = object;
  83346. var boundingInfo = mesh.getBoundingInfo();
  83347. //calculate the correct body position:
  83348. var rotationQuaternion = mesh.rotationQuaternion;
  83349. mesh.rotationQuaternion = this._tmpUnityRotation;
  83350. mesh.computeWorldMatrix(true);
  83351. //get original center with no rotation
  83352. var c = center.clone();
  83353. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83354. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83355. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83356. mesh.setPreTransformMatrix(p);
  83357. mesh.computeWorldMatrix(true);
  83358. //calculate the translation
  83359. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83360. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83361. //add it inverted to the delta
  83362. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83363. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83364. //rotation is back
  83365. mesh.rotationQuaternion = rotationQuaternion;
  83366. mesh.setPreTransformMatrix(oldPivot);
  83367. mesh.computeWorldMatrix(true);
  83368. }
  83369. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83370. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83371. //this._tmpPosition.copyFrom(object.position);
  83372. }
  83373. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83374. //Now update the impostor object
  83375. impostor.physicsBody.position.copy(this._tmpPosition);
  83376. impostor.physicsBody.quaternion.copy(quaternion);
  83377. };
  83378. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83379. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83380. if (impostor.object.rotationQuaternion) {
  83381. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83382. }
  83383. };
  83384. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83385. impostor.physicsBody.position.copy(newPosition);
  83386. impostor.physicsBody.quaternion.copy(newRotation);
  83387. };
  83388. CannonJSPlugin.prototype.isSupported = function () {
  83389. return this.BJSCANNON !== undefined;
  83390. };
  83391. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83392. impostor.physicsBody.velocity.copy(velocity);
  83393. };
  83394. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83395. impostor.physicsBody.angularVelocity.copy(velocity);
  83396. };
  83397. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83398. var v = impostor.physicsBody.velocity;
  83399. if (!v) {
  83400. return null;
  83401. }
  83402. return new BABYLON.Vector3(v.x, v.y, v.z);
  83403. };
  83404. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83405. var v = impostor.physicsBody.angularVelocity;
  83406. if (!v) {
  83407. return null;
  83408. }
  83409. return new BABYLON.Vector3(v.x, v.y, v.z);
  83410. };
  83411. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83412. impostor.physicsBody.mass = mass;
  83413. impostor.physicsBody.updateMassProperties();
  83414. };
  83415. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83416. return impostor.physicsBody.mass;
  83417. };
  83418. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83419. return impostor.physicsBody.material.friction;
  83420. };
  83421. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83422. impostor.physicsBody.material.friction = friction;
  83423. };
  83424. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83425. return impostor.physicsBody.material.restitution;
  83426. };
  83427. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83428. impostor.physicsBody.material.restitution = restitution;
  83429. };
  83430. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83431. impostor.physicsBody.sleep();
  83432. };
  83433. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83434. impostor.physicsBody.wakeUp();
  83435. };
  83436. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83437. joint.physicsJoint.distance = maxDistance;
  83438. };
  83439. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83440. // if (!motorIndex) {
  83441. // joint.physicsJoint.enableMotor();
  83442. // }
  83443. // }
  83444. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83445. // if (!motorIndex) {
  83446. // joint.physicsJoint.disableMotor();
  83447. // }
  83448. // }
  83449. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83450. if (!motorIndex) {
  83451. joint.physicsJoint.enableMotor();
  83452. joint.physicsJoint.setMotorSpeed(speed);
  83453. if (maxForce) {
  83454. this.setLimit(joint, maxForce);
  83455. }
  83456. }
  83457. };
  83458. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83459. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83460. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83461. };
  83462. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83463. var body = impostor.physicsBody;
  83464. mesh.position.x = body.position.x;
  83465. mesh.position.y = body.position.y;
  83466. mesh.position.z = body.position.z;
  83467. if (mesh.rotationQuaternion) {
  83468. mesh.rotationQuaternion.x = body.quaternion.x;
  83469. mesh.rotationQuaternion.y = body.quaternion.y;
  83470. mesh.rotationQuaternion.z = body.quaternion.z;
  83471. mesh.rotationQuaternion.w = body.quaternion.w;
  83472. }
  83473. };
  83474. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83475. var shape = impostor.physicsBody.shapes[0];
  83476. return shape.boundingSphereRadius;
  83477. };
  83478. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83479. var shape = impostor.physicsBody.shapes[0];
  83480. result.x = shape.halfExtents.x * 2;
  83481. result.y = shape.halfExtents.y * 2;
  83482. result.z = shape.halfExtents.z * 2;
  83483. };
  83484. CannonJSPlugin.prototype.dispose = function () {
  83485. };
  83486. CannonJSPlugin.prototype._extendNamespace = function () {
  83487. //this will force cannon to execute at least one step when using interpolation
  83488. var step_tmp1 = new this.BJSCANNON.Vec3();
  83489. var Engine = this.BJSCANNON;
  83490. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83491. maxSubSteps = maxSubSteps || 10;
  83492. timeSinceLastCalled = timeSinceLastCalled || 0;
  83493. if (timeSinceLastCalled === 0) {
  83494. this.internalStep(dt);
  83495. this.time += dt;
  83496. }
  83497. else {
  83498. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83499. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83500. var t0 = performance.now();
  83501. for (var i = 0; i !== internalSteps; i++) {
  83502. this.internalStep(dt);
  83503. if (performance.now() - t0 > dt * 1000) {
  83504. break;
  83505. }
  83506. }
  83507. this.time += timeSinceLastCalled;
  83508. var h = this.time % dt;
  83509. var h_div_dt = h / dt;
  83510. var interpvelo = step_tmp1;
  83511. var bodies = this.bodies;
  83512. for (var j = 0; j !== bodies.length; j++) {
  83513. var b = bodies[j];
  83514. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83515. b.position.vsub(b.previousPosition, interpvelo);
  83516. interpvelo.scale(h_div_dt, interpvelo);
  83517. b.position.vadd(interpvelo, b.interpolatedPosition);
  83518. }
  83519. else {
  83520. b.interpolatedPosition.copy(b.position);
  83521. b.interpolatedQuaternion.copy(b.quaternion);
  83522. }
  83523. }
  83524. }
  83525. };
  83526. };
  83527. return CannonJSPlugin;
  83528. }());
  83529. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83530. })(BABYLON || (BABYLON = {}));
  83531. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83532. var BABYLON;
  83533. (function (BABYLON) {
  83534. var OimoJSPlugin = /** @class */ (function () {
  83535. function OimoJSPlugin(iterations) {
  83536. this.name = "OimoJSPlugin";
  83537. this._tmpImpostorsArray = [];
  83538. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83539. this.BJSOIMO = OIMO;
  83540. this.world = new this.BJSOIMO.World({
  83541. iterations: iterations
  83542. });
  83543. this.world.clear();
  83544. }
  83545. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83546. this.world.gravity.copy(gravity);
  83547. };
  83548. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83549. this.world.timeStep = timeStep;
  83550. };
  83551. OimoJSPlugin.prototype.getTimeStep = function () {
  83552. return this.world.timeStep;
  83553. };
  83554. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83555. var _this = this;
  83556. impostors.forEach(function (impostor) {
  83557. impostor.beforeStep();
  83558. });
  83559. this.world.step();
  83560. impostors.forEach(function (impostor) {
  83561. impostor.afterStep();
  83562. //update the ordered impostors array
  83563. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83564. });
  83565. //check for collisions
  83566. var contact = this.world.contacts;
  83567. while (contact !== null) {
  83568. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83569. contact = contact.next;
  83570. continue;
  83571. }
  83572. //is this body colliding with any other? get the impostor
  83573. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83574. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83575. if (!mainImpostor || !collidingImpostor) {
  83576. contact = contact.next;
  83577. continue;
  83578. }
  83579. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83580. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83581. contact = contact.next;
  83582. }
  83583. };
  83584. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83585. var mass = impostor.physicsBody.mass;
  83586. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83587. };
  83588. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83589. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83590. this.applyImpulse(impostor, force, contactPoint);
  83591. };
  83592. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83593. var _this = this;
  83594. //parent-child relationship. Does this impostor has a parent impostor?
  83595. if (impostor.parent) {
  83596. if (impostor.physicsBody) {
  83597. this.removePhysicsBody(impostor);
  83598. //TODO is that needed?
  83599. impostor.forceUpdate();
  83600. }
  83601. return;
  83602. }
  83603. if (impostor.isBodyInitRequired()) {
  83604. var bodyConfig = {
  83605. name: impostor.uniqueId,
  83606. //Oimo must have mass, also for static objects.
  83607. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83608. size: [],
  83609. type: [],
  83610. pos: [],
  83611. posShape: [],
  83612. rot: [],
  83613. rotShape: [],
  83614. move: impostor.getParam("mass") !== 0,
  83615. density: impostor.getParam("mass"),
  83616. friction: impostor.getParam("friction"),
  83617. restitution: impostor.getParam("restitution"),
  83618. //Supporting older versions of Oimo
  83619. world: this.world
  83620. };
  83621. var impostors = [impostor];
  83622. var addToArray = function (parent) {
  83623. if (!parent.getChildMeshes)
  83624. return;
  83625. parent.getChildMeshes().forEach(function (m) {
  83626. if (m.physicsImpostor) {
  83627. impostors.push(m.physicsImpostor);
  83628. //m.physicsImpostor._init();
  83629. }
  83630. });
  83631. };
  83632. addToArray(impostor.object);
  83633. var checkWithEpsilon_1 = function (value) {
  83634. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83635. };
  83636. impostors.forEach(function (i) {
  83637. if (!i.object.rotationQuaternion) {
  83638. return;
  83639. }
  83640. //get the correct bounding box
  83641. var oldQuaternion = i.object.rotationQuaternion;
  83642. var rot = oldQuaternion.toEulerAngles();
  83643. var extendSize = i.getObjectExtendSize();
  83644. var radToDeg = 57.295779513082320876;
  83645. if (i === impostor) {
  83646. var center = impostor.getObjectCenter();
  83647. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83648. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83649. //Can also use Array.prototype.push.apply
  83650. bodyConfig.pos.push(center.x);
  83651. bodyConfig.pos.push(center.y);
  83652. bodyConfig.pos.push(center.z);
  83653. bodyConfig.posShape.push(0, 0, 0);
  83654. //tmp solution
  83655. bodyConfig.rot.push(rot.x * radToDeg);
  83656. bodyConfig.rot.push(rot.y * radToDeg);
  83657. bodyConfig.rot.push(rot.z * radToDeg);
  83658. bodyConfig.rotShape.push(0, 0, 0);
  83659. }
  83660. else {
  83661. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83662. bodyConfig.posShape.push(localPosition.x);
  83663. bodyConfig.posShape.push(localPosition.y);
  83664. bodyConfig.posShape.push(localPosition.z);
  83665. bodyConfig.pos.push(0, 0, 0);
  83666. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83667. bodyConfig.rot.push(0);
  83668. bodyConfig.rot.push(0);
  83669. bodyConfig.rot.push(0);
  83670. bodyConfig.rotShape.push(rot.x * radToDeg);
  83671. bodyConfig.rotShape.push(rot.y * radToDeg);
  83672. bodyConfig.rotShape.push(rot.z * radToDeg);
  83673. }
  83674. // register mesh
  83675. switch (i.type) {
  83676. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83677. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83678. case BABYLON.PhysicsImpostor.SphereImpostor:
  83679. var radiusX = extendSize.x;
  83680. var radiusY = extendSize.y;
  83681. var radiusZ = extendSize.z;
  83682. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83683. bodyConfig.type.push('sphere');
  83684. //due to the way oimo works with compounds, add 3 times
  83685. bodyConfig.size.push(size);
  83686. bodyConfig.size.push(size);
  83687. bodyConfig.size.push(size);
  83688. break;
  83689. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83690. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83691. var sizeY = checkWithEpsilon_1(extendSize.y);
  83692. bodyConfig.type.push('cylinder');
  83693. bodyConfig.size.push(sizeX);
  83694. bodyConfig.size.push(sizeY);
  83695. //due to the way oimo works with compounds, add one more value.
  83696. bodyConfig.size.push(sizeY);
  83697. break;
  83698. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83699. case BABYLON.PhysicsImpostor.BoxImpostor:
  83700. default:
  83701. var sizeX = checkWithEpsilon_1(extendSize.x);
  83702. var sizeY = checkWithEpsilon_1(extendSize.y);
  83703. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83704. bodyConfig.type.push('box');
  83705. //if (i === impostor) {
  83706. bodyConfig.size.push(sizeX);
  83707. bodyConfig.size.push(sizeY);
  83708. bodyConfig.size.push(sizeZ);
  83709. //} else {
  83710. // bodyConfig.size.push(0,0,0);
  83711. //}
  83712. break;
  83713. }
  83714. //actually not needed, but hey...
  83715. i.object.rotationQuaternion = oldQuaternion;
  83716. });
  83717. impostor.physicsBody = this.world.add(bodyConfig);
  83718. }
  83719. else {
  83720. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83721. }
  83722. impostor.setDeltaPosition(this._tmpPositionVector);
  83723. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83724. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83725. };
  83726. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83727. //impostor.physicsBody.dispose();
  83728. //Same as : (older oimo versions)
  83729. this.world.removeRigidBody(impostor.physicsBody);
  83730. };
  83731. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83732. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83733. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83734. if (!mainBody || !connectedBody) {
  83735. return;
  83736. }
  83737. var jointData = impostorJoint.joint.jointData;
  83738. var options = jointData.nativeParams || {};
  83739. var type;
  83740. var nativeJointData = {
  83741. body1: mainBody,
  83742. body2: connectedBody,
  83743. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83744. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83745. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83746. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83747. min: options.min,
  83748. max: options.max,
  83749. collision: options.collision || jointData.collision,
  83750. spring: options.spring,
  83751. //supporting older version of Oimo
  83752. world: this.world
  83753. };
  83754. switch (impostorJoint.joint.type) {
  83755. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83756. type = "jointBall";
  83757. break;
  83758. case BABYLON.PhysicsJoint.SpringJoint:
  83759. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83760. var springData = jointData;
  83761. nativeJointData.min = springData.length || nativeJointData.min;
  83762. //Max should also be set, just make sure it is at least min
  83763. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83764. case BABYLON.PhysicsJoint.DistanceJoint:
  83765. type = "jointDistance";
  83766. nativeJointData.max = jointData.maxDistance;
  83767. break;
  83768. case BABYLON.PhysicsJoint.PrismaticJoint:
  83769. type = "jointPrisme";
  83770. break;
  83771. case BABYLON.PhysicsJoint.SliderJoint:
  83772. type = "jointSlide";
  83773. break;
  83774. case BABYLON.PhysicsJoint.WheelJoint:
  83775. type = "jointWheel";
  83776. break;
  83777. case BABYLON.PhysicsJoint.HingeJoint:
  83778. default:
  83779. type = "jointHinge";
  83780. break;
  83781. }
  83782. nativeJointData.type = type;
  83783. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83784. };
  83785. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83786. //Bug in Oimo prevents us from disposing a joint in the playground
  83787. //joint.joint.physicsJoint.dispose();
  83788. //So we will bruteforce it!
  83789. try {
  83790. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83791. }
  83792. catch (e) {
  83793. BABYLON.Tools.Warn(e);
  83794. }
  83795. };
  83796. OimoJSPlugin.prototype.isSupported = function () {
  83797. return this.BJSOIMO !== undefined;
  83798. };
  83799. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83800. if (!impostor.physicsBody.sleeping) {
  83801. //TODO check that
  83802. /*if (impostor.physicsBody.shapes.next) {
  83803. var parentShape = this._getLastShape(impostor.physicsBody);
  83804. impostor.object.position.copyFrom(parentShape.position);
  83805. console.log(parentShape.position);
  83806. } else {*/
  83807. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83808. //}
  83809. if (impostor.object.rotationQuaternion) {
  83810. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83811. }
  83812. }
  83813. };
  83814. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83815. var body = impostor.physicsBody;
  83816. body.position.copy(newPosition);
  83817. body.orientation.copy(newRotation);
  83818. body.syncShapes();
  83819. body.awake();
  83820. };
  83821. /*private _getLastShape(body: any): any {
  83822. var lastShape = body.shapes;
  83823. while (lastShape.next) {
  83824. lastShape = lastShape.next;
  83825. }
  83826. return lastShape;
  83827. }*/
  83828. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83829. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83830. };
  83831. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83832. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83833. };
  83834. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83835. var v = impostor.physicsBody.linearVelocity;
  83836. if (!v) {
  83837. return null;
  83838. }
  83839. return new BABYLON.Vector3(v.x, v.y, v.z);
  83840. };
  83841. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83842. var v = impostor.physicsBody.angularVelocity;
  83843. if (!v) {
  83844. return null;
  83845. }
  83846. return new BABYLON.Vector3(v.x, v.y, v.z);
  83847. };
  83848. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83849. var staticBody = mass === 0;
  83850. //this will actually set the body's density and not its mass.
  83851. //But this is how oimo treats the mass variable.
  83852. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83853. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83854. };
  83855. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83856. return impostor.physicsBody.shapes.density;
  83857. };
  83858. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83859. return impostor.physicsBody.shapes.friction;
  83860. };
  83861. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83862. impostor.physicsBody.shapes.friction = friction;
  83863. };
  83864. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83865. return impostor.physicsBody.shapes.restitution;
  83866. };
  83867. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83868. impostor.physicsBody.shapes.restitution = restitution;
  83869. };
  83870. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83871. impostor.physicsBody.sleep();
  83872. };
  83873. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83874. impostor.physicsBody.awake();
  83875. };
  83876. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83877. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83878. if (minDistance !== void 0) {
  83879. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83880. }
  83881. };
  83882. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83883. //TODO separate rotational and transational motors.
  83884. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83885. if (motor) {
  83886. motor.setMotor(speed, maxForce);
  83887. }
  83888. };
  83889. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83890. //TODO separate rotational and transational motors.
  83891. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83892. if (motor) {
  83893. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83894. }
  83895. };
  83896. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83897. var body = impostor.physicsBody;
  83898. mesh.position.x = body.position.x;
  83899. mesh.position.y = body.position.y;
  83900. mesh.position.z = body.position.z;
  83901. if (mesh.rotationQuaternion) {
  83902. mesh.rotationQuaternion.x = body.orientation.x;
  83903. mesh.rotationQuaternion.y = body.orientation.y;
  83904. mesh.rotationQuaternion.z = body.orientation.z;
  83905. mesh.rotationQuaternion.w = body.orientation.s;
  83906. }
  83907. };
  83908. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83909. return impostor.physicsBody.shapes.radius;
  83910. };
  83911. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83912. var shape = impostor.physicsBody.shapes;
  83913. result.x = shape.halfWidth * 2;
  83914. result.y = shape.halfHeight * 2;
  83915. result.z = shape.halfDepth * 2;
  83916. };
  83917. OimoJSPlugin.prototype.dispose = function () {
  83918. this.world.clear();
  83919. };
  83920. return OimoJSPlugin;
  83921. }());
  83922. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83923. })(BABYLON || (BABYLON = {}));
  83924. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83925. var BABYLON;
  83926. (function (BABYLON) {
  83927. /*
  83928. * Based on jsTGALoader - Javascript loader for TGA file
  83929. * By Vincent Thibault
  83930. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83931. */
  83932. var TGATools = /** @class */ (function () {
  83933. function TGATools() {
  83934. }
  83935. TGATools.GetTGAHeader = function (data) {
  83936. var offset = 0;
  83937. var header = {
  83938. id_length: data[offset++],
  83939. colormap_type: data[offset++],
  83940. image_type: data[offset++],
  83941. colormap_index: data[offset++] | data[offset++] << 8,
  83942. colormap_length: data[offset++] | data[offset++] << 8,
  83943. colormap_size: data[offset++],
  83944. origin: [
  83945. data[offset++] | data[offset++] << 8,
  83946. data[offset++] | data[offset++] << 8
  83947. ],
  83948. width: data[offset++] | data[offset++] << 8,
  83949. height: data[offset++] | data[offset++] << 8,
  83950. pixel_size: data[offset++],
  83951. flags: data[offset++]
  83952. };
  83953. return header;
  83954. };
  83955. TGATools.UploadContent = function (gl, data) {
  83956. // Not enough data to contain header ?
  83957. if (data.length < 19) {
  83958. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83959. return;
  83960. }
  83961. // Read Header
  83962. var offset = 18;
  83963. var header = TGATools.GetTGAHeader(data);
  83964. // Assume it's a valid Targa file.
  83965. if (header.id_length + offset > data.length) {
  83966. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83967. return;
  83968. }
  83969. // Skip not needed data
  83970. offset += header.id_length;
  83971. var use_rle = false;
  83972. var use_pal = false;
  83973. var use_grey = false;
  83974. // Get some informations.
  83975. switch (header.image_type) {
  83976. case TGATools._TYPE_RLE_INDEXED:
  83977. use_rle = true;
  83978. case TGATools._TYPE_INDEXED:
  83979. use_pal = true;
  83980. break;
  83981. case TGATools._TYPE_RLE_RGB:
  83982. use_rle = true;
  83983. case TGATools._TYPE_RGB:
  83984. // use_rgb = true;
  83985. break;
  83986. case TGATools._TYPE_RLE_GREY:
  83987. use_rle = true;
  83988. case TGATools._TYPE_GREY:
  83989. use_grey = true;
  83990. break;
  83991. }
  83992. var pixel_data;
  83993. // var numAlphaBits = header.flags & 0xf;
  83994. var pixel_size = header.pixel_size >> 3;
  83995. var pixel_total = header.width * header.height * pixel_size;
  83996. // Read palettes
  83997. var palettes;
  83998. if (use_pal) {
  83999. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84000. }
  84001. // Read LRE
  84002. if (use_rle) {
  84003. pixel_data = new Uint8Array(pixel_total);
  84004. var c, count, i;
  84005. var localOffset = 0;
  84006. var pixels = new Uint8Array(pixel_size);
  84007. while (offset < pixel_total && localOffset < pixel_total) {
  84008. c = data[offset++];
  84009. count = (c & 0x7f) + 1;
  84010. // RLE pixels
  84011. if (c & 0x80) {
  84012. // Bind pixel tmp array
  84013. for (i = 0; i < pixel_size; ++i) {
  84014. pixels[i] = data[offset++];
  84015. }
  84016. // Copy pixel array
  84017. for (i = 0; i < count; ++i) {
  84018. pixel_data.set(pixels, localOffset + i * pixel_size);
  84019. }
  84020. localOffset += pixel_size * count;
  84021. }
  84022. // Raw pixels
  84023. else {
  84024. count *= pixel_size;
  84025. for (i = 0; i < count; ++i) {
  84026. pixel_data[localOffset + i] = data[offset++];
  84027. }
  84028. localOffset += count;
  84029. }
  84030. }
  84031. }
  84032. // RAW Pixels
  84033. else {
  84034. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84035. }
  84036. // Load to texture
  84037. var x_start, y_start, x_step, y_step, y_end, x_end;
  84038. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84039. default:
  84040. case TGATools._ORIGIN_UL:
  84041. x_start = 0;
  84042. x_step = 1;
  84043. x_end = header.width;
  84044. y_start = 0;
  84045. y_step = 1;
  84046. y_end = header.height;
  84047. break;
  84048. case TGATools._ORIGIN_BL:
  84049. x_start = 0;
  84050. x_step = 1;
  84051. x_end = header.width;
  84052. y_start = header.height - 1;
  84053. y_step = -1;
  84054. y_end = -1;
  84055. break;
  84056. case TGATools._ORIGIN_UR:
  84057. x_start = header.width - 1;
  84058. x_step = -1;
  84059. x_end = -1;
  84060. y_start = 0;
  84061. y_step = 1;
  84062. y_end = header.height;
  84063. break;
  84064. case TGATools._ORIGIN_BR:
  84065. x_start = header.width - 1;
  84066. x_step = -1;
  84067. x_end = -1;
  84068. y_start = header.height - 1;
  84069. y_step = -1;
  84070. y_end = -1;
  84071. break;
  84072. }
  84073. // Load the specify method
  84074. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84075. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84076. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84077. };
  84078. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84079. var image = pixel_data, colormap = palettes;
  84080. var width = header.width, height = header.height;
  84081. var color, i = 0, x, y;
  84082. var imageData = new Uint8Array(width * height * 4);
  84083. for (y = y_start; y !== y_end; y += y_step) {
  84084. for (x = x_start; x !== x_end; x += x_step, i++) {
  84085. color = image[i];
  84086. imageData[(x + width * y) * 4 + 3] = 255;
  84087. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84088. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84089. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84090. }
  84091. }
  84092. return imageData;
  84093. };
  84094. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84095. var image = pixel_data;
  84096. var width = header.width, height = header.height;
  84097. var color, i = 0, x, y;
  84098. var imageData = new Uint8Array(width * height * 4);
  84099. for (y = y_start; y !== y_end; y += y_step) {
  84100. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84101. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84102. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84103. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84104. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84105. imageData[(x + width * y) * 4 + 0] = r;
  84106. imageData[(x + width * y) * 4 + 1] = g;
  84107. imageData[(x + width * y) * 4 + 2] = b;
  84108. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84109. }
  84110. }
  84111. return imageData;
  84112. };
  84113. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84114. var image = pixel_data;
  84115. var width = header.width, height = header.height;
  84116. var i = 0, x, y;
  84117. var imageData = new Uint8Array(width * height * 4);
  84118. for (y = y_start; y !== y_end; y += y_step) {
  84119. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84120. imageData[(x + width * y) * 4 + 3] = 255;
  84121. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84122. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84123. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84124. }
  84125. }
  84126. return imageData;
  84127. };
  84128. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84129. var image = pixel_data;
  84130. var width = header.width, height = header.height;
  84131. var i = 0, x, y;
  84132. var imageData = new Uint8Array(width * height * 4);
  84133. for (y = y_start; y !== y_end; y += y_step) {
  84134. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84135. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84136. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84137. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84138. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84139. }
  84140. }
  84141. return imageData;
  84142. };
  84143. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84144. var image = pixel_data;
  84145. var width = header.width, height = header.height;
  84146. var color, i = 0, x, y;
  84147. var imageData = new Uint8Array(width * height * 4);
  84148. for (y = y_start; y !== y_end; y += y_step) {
  84149. for (x = x_start; x !== x_end; x += x_step, i++) {
  84150. color = image[i];
  84151. imageData[(x + width * y) * 4 + 0] = color;
  84152. imageData[(x + width * y) * 4 + 1] = color;
  84153. imageData[(x + width * y) * 4 + 2] = color;
  84154. imageData[(x + width * y) * 4 + 3] = 255;
  84155. }
  84156. }
  84157. return imageData;
  84158. };
  84159. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84160. var image = pixel_data;
  84161. var width = header.width, height = header.height;
  84162. var i = 0, x, y;
  84163. var imageData = new Uint8Array(width * height * 4);
  84164. for (y = y_start; y !== y_end; y += y_step) {
  84165. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84166. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84167. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84168. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84169. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84170. }
  84171. }
  84172. return imageData;
  84173. };
  84174. //private static _TYPE_NO_DATA = 0;
  84175. TGATools._TYPE_INDEXED = 1;
  84176. TGATools._TYPE_RGB = 2;
  84177. TGATools._TYPE_GREY = 3;
  84178. TGATools._TYPE_RLE_INDEXED = 9;
  84179. TGATools._TYPE_RLE_RGB = 10;
  84180. TGATools._TYPE_RLE_GREY = 11;
  84181. TGATools._ORIGIN_MASK = 0x30;
  84182. TGATools._ORIGIN_SHIFT = 0x04;
  84183. TGATools._ORIGIN_BL = 0x00;
  84184. TGATools._ORIGIN_BR = 0x01;
  84185. TGATools._ORIGIN_UL = 0x02;
  84186. TGATools._ORIGIN_UR = 0x03;
  84187. return TGATools;
  84188. }());
  84189. BABYLON.TGATools = TGATools;
  84190. })(BABYLON || (BABYLON = {}));
  84191. //# sourceMappingURL=babylon.tga.js.map
  84192. var BABYLON;
  84193. (function (BABYLON) {
  84194. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84195. // All values and structures referenced from:
  84196. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84197. var DDS_MAGIC = 0x20534444;
  84198. var
  84199. //DDSD_CAPS = 0x1,
  84200. //DDSD_HEIGHT = 0x2,
  84201. //DDSD_WIDTH = 0x4,
  84202. //DDSD_PITCH = 0x8,
  84203. //DDSD_PIXELFORMAT = 0x1000,
  84204. DDSD_MIPMAPCOUNT = 0x20000;
  84205. //DDSD_LINEARSIZE = 0x80000,
  84206. //DDSD_DEPTH = 0x800000;
  84207. // var DDSCAPS_COMPLEX = 0x8,
  84208. // DDSCAPS_MIPMAP = 0x400000,
  84209. // DDSCAPS_TEXTURE = 0x1000;
  84210. var DDSCAPS2_CUBEMAP = 0x200;
  84211. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84212. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84213. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84214. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84215. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84216. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84217. // DDSCAPS2_VOLUME = 0x200000;
  84218. var
  84219. //DDPF_ALPHAPIXELS = 0x1,
  84220. //DDPF_ALPHA = 0x2,
  84221. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84222. //DDPF_YUV = 0x200,
  84223. DDPF_LUMINANCE = 0x20000;
  84224. function FourCCToInt32(value) {
  84225. return value.charCodeAt(0) +
  84226. (value.charCodeAt(1) << 8) +
  84227. (value.charCodeAt(2) << 16) +
  84228. (value.charCodeAt(3) << 24);
  84229. }
  84230. function Int32ToFourCC(value) {
  84231. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84232. }
  84233. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84234. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84235. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84236. var FOURCC_DX10 = FourCCToInt32("DX10");
  84237. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84238. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84239. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84240. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84241. var headerLengthInt = 31; // The header length in 32 bit ints
  84242. // Offsets into the header array
  84243. var off_magic = 0;
  84244. var off_size = 1;
  84245. var off_flags = 2;
  84246. var off_height = 3;
  84247. var off_width = 4;
  84248. var off_mipmapCount = 7;
  84249. var off_pfFlags = 20;
  84250. var off_pfFourCC = 21;
  84251. var off_RGBbpp = 22;
  84252. var off_RMask = 23;
  84253. var off_GMask = 24;
  84254. var off_BMask = 25;
  84255. var off_AMask = 26;
  84256. // var off_caps1 = 27;
  84257. var off_caps2 = 28;
  84258. // var off_caps3 = 29;
  84259. // var off_caps4 = 30;
  84260. var off_dxgiFormat = 32;
  84261. ;
  84262. var DDSTools = /** @class */ (function () {
  84263. function DDSTools() {
  84264. }
  84265. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84266. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84267. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84268. var mipmapCount = 1;
  84269. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84270. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84271. }
  84272. var fourCC = header[off_pfFourCC];
  84273. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84274. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84275. switch (fourCC) {
  84276. case FOURCC_D3DFMT_R16G16B16A16F:
  84277. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84278. break;
  84279. case FOURCC_D3DFMT_R32G32B32A32F:
  84280. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84281. break;
  84282. case FOURCC_DX10:
  84283. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84284. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84285. break;
  84286. }
  84287. }
  84288. return {
  84289. width: header[off_width],
  84290. height: header[off_height],
  84291. mipmapCount: mipmapCount,
  84292. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84293. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84294. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84295. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84296. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84297. dxgiFormat: dxgiFormat,
  84298. textureType: textureType
  84299. };
  84300. };
  84301. DDSTools._ToHalfFloat = function (value) {
  84302. if (!DDSTools._FloatView) {
  84303. DDSTools._FloatView = new Float32Array(1);
  84304. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84305. }
  84306. DDSTools._FloatView[0] = value;
  84307. var x = DDSTools._Int32View[0];
  84308. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84309. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84310. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84311. /* If zero, or denormal, or exponent underflows too much for a denormal
  84312. * half, return signed zero. */
  84313. if (e < 103) {
  84314. return bits;
  84315. }
  84316. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84317. if (e > 142) {
  84318. bits |= 0x7c00;
  84319. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84320. * not Inf, so make sure we set one mantissa bit too. */
  84321. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84322. return bits;
  84323. }
  84324. /* If exponent underflows but not too much, return a denormal */
  84325. if (e < 113) {
  84326. m |= 0x0800;
  84327. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84328. * to 1, which is OK. */
  84329. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84330. return bits;
  84331. }
  84332. bits |= ((e - 112) << 10) | (m >> 1);
  84333. bits += m & 1;
  84334. return bits;
  84335. };
  84336. DDSTools._FromHalfFloat = function (value) {
  84337. var s = (value & 0x8000) >> 15;
  84338. var e = (value & 0x7C00) >> 10;
  84339. var f = value & 0x03FF;
  84340. if (e === 0) {
  84341. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84342. }
  84343. else if (e == 0x1F) {
  84344. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84345. }
  84346. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84347. };
  84348. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84349. var destArray = new Float32Array(dataLength);
  84350. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84351. var index = 0;
  84352. for (var y = 0; y < height; y++) {
  84353. for (var x = 0; x < width; x++) {
  84354. var srcPos = (x + y * width) * 4;
  84355. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84356. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84357. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84358. if (DDSTools.StoreLODInAlphaChannel) {
  84359. destArray[index + 3] = lod;
  84360. }
  84361. else {
  84362. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84363. }
  84364. index += 4;
  84365. }
  84366. }
  84367. return destArray;
  84368. };
  84369. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84370. if (DDSTools.StoreLODInAlphaChannel) {
  84371. var destArray = new Uint16Array(dataLength);
  84372. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84373. var index = 0;
  84374. for (var y = 0; y < height; y++) {
  84375. for (var x = 0; x < width; x++) {
  84376. var srcPos = (x + y * width) * 4;
  84377. destArray[index] = srcData[srcPos];
  84378. destArray[index + 1] = srcData[srcPos + 1];
  84379. destArray[index + 2] = srcData[srcPos + 2];
  84380. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84381. index += 4;
  84382. }
  84383. }
  84384. return destArray;
  84385. }
  84386. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84387. };
  84388. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84389. if (DDSTools.StoreLODInAlphaChannel) {
  84390. var destArray = new Float32Array(dataLength);
  84391. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84392. var index = 0;
  84393. for (var y = 0; y < height; y++) {
  84394. for (var x = 0; x < width; x++) {
  84395. var srcPos = (x + y * width) * 4;
  84396. destArray[index] = srcData[srcPos];
  84397. destArray[index + 1] = srcData[srcPos + 1];
  84398. destArray[index + 2] = srcData[srcPos + 2];
  84399. destArray[index + 3] = lod;
  84400. index += 4;
  84401. }
  84402. }
  84403. return destArray;
  84404. }
  84405. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84406. };
  84407. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84408. var destArray = new Uint8Array(dataLength);
  84409. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84410. var index = 0;
  84411. for (var y = 0; y < height; y++) {
  84412. for (var x = 0; x < width; x++) {
  84413. var srcPos = (x + y * width) * 4;
  84414. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84415. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84416. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84417. if (DDSTools.StoreLODInAlphaChannel) {
  84418. destArray[index + 3] = lod;
  84419. }
  84420. else {
  84421. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84422. }
  84423. index += 4;
  84424. }
  84425. }
  84426. return destArray;
  84427. };
  84428. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84429. var destArray = new Uint8Array(dataLength);
  84430. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84431. var index = 0;
  84432. for (var y = 0; y < height; y++) {
  84433. for (var x = 0; x < width; x++) {
  84434. var srcPos = (x + y * width) * 4;
  84435. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84436. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84437. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84438. if (DDSTools.StoreLODInAlphaChannel) {
  84439. destArray[index + 3] = lod;
  84440. }
  84441. else {
  84442. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84443. }
  84444. index += 4;
  84445. }
  84446. }
  84447. return destArray;
  84448. };
  84449. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84450. var byteArray = new Uint8Array(dataLength);
  84451. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84452. var index = 0;
  84453. for (var y = 0; y < height; y++) {
  84454. for (var x = 0; x < width; x++) {
  84455. var srcPos = (x + y * width) * 4;
  84456. byteArray[index] = srcData[srcPos + rOffset];
  84457. byteArray[index + 1] = srcData[srcPos + gOffset];
  84458. byteArray[index + 2] = srcData[srcPos + bOffset];
  84459. byteArray[index + 3] = srcData[srcPos + aOffset];
  84460. index += 4;
  84461. }
  84462. }
  84463. return byteArray;
  84464. };
  84465. DDSTools._ExtractLongWordOrder = function (value) {
  84466. if (value === 0 || value === 255 || value === -16777216) {
  84467. return 0;
  84468. }
  84469. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84470. };
  84471. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84472. var byteArray = new Uint8Array(dataLength);
  84473. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84474. var index = 0;
  84475. for (var y = 0; y < height; y++) {
  84476. for (var x = 0; x < width; x++) {
  84477. var srcPos = (x + y * width) * 3;
  84478. byteArray[index] = srcData[srcPos + rOffset];
  84479. byteArray[index + 1] = srcData[srcPos + gOffset];
  84480. byteArray[index + 2] = srcData[srcPos + bOffset];
  84481. index += 3;
  84482. }
  84483. }
  84484. return byteArray;
  84485. };
  84486. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84487. var byteArray = new Uint8Array(dataLength);
  84488. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84489. var index = 0;
  84490. for (var y = 0; y < height; y++) {
  84491. for (var x = 0; x < width; x++) {
  84492. var srcPos = (x + y * width);
  84493. byteArray[index] = srcData[srcPos];
  84494. index++;
  84495. }
  84496. }
  84497. return byteArray;
  84498. };
  84499. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84500. if (lodIndex === void 0) { lodIndex = -1; }
  84501. var sphericalPolynomialFaces = null;
  84502. if (info.sphericalPolynomial) {
  84503. sphericalPolynomialFaces = new Array();
  84504. }
  84505. var ext = engine.getCaps().s3tc;
  84506. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84507. var fourCC, width, height, dataLength = 0, dataOffset;
  84508. var byteArray, mipmapCount, mip;
  84509. var internalFormat = 0;
  84510. var format = 0;
  84511. var blockBytes = 1;
  84512. if (header[off_magic] !== DDS_MAGIC) {
  84513. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84514. return;
  84515. }
  84516. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84517. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84518. return;
  84519. }
  84520. if (info.isCompressed && !ext) {
  84521. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84522. return;
  84523. }
  84524. var bpp = header[off_RGBbpp];
  84525. dataOffset = header[off_size] + 4;
  84526. var computeFormats = false;
  84527. if (info.isFourCC) {
  84528. fourCC = header[off_pfFourCC];
  84529. switch (fourCC) {
  84530. case FOURCC_DXT1:
  84531. blockBytes = 8;
  84532. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84533. break;
  84534. case FOURCC_DXT3:
  84535. blockBytes = 16;
  84536. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84537. break;
  84538. case FOURCC_DXT5:
  84539. blockBytes = 16;
  84540. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84541. break;
  84542. case FOURCC_D3DFMT_R16G16B16A16F:
  84543. computeFormats = true;
  84544. break;
  84545. case FOURCC_D3DFMT_R32G32B32A32F:
  84546. computeFormats = true;
  84547. break;
  84548. case FOURCC_DX10:
  84549. // There is an additionnal header so dataOffset need to be changed
  84550. dataOffset += 5 * 4; // 5 uints
  84551. var supported = false;
  84552. switch (info.dxgiFormat) {
  84553. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84554. computeFormats = true;
  84555. supported = true;
  84556. break;
  84557. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84558. info.isRGB = true;
  84559. info.isFourCC = false;
  84560. bpp = 32;
  84561. supported = true;
  84562. break;
  84563. }
  84564. if (supported) {
  84565. break;
  84566. }
  84567. default:
  84568. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84569. return;
  84570. }
  84571. }
  84572. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84573. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84574. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84575. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84576. if (computeFormats) {
  84577. format = engine._getWebGLTextureType(info.textureType);
  84578. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84579. }
  84580. mipmapCount = 1;
  84581. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84582. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84583. }
  84584. for (var face = 0; face < faces; face++) {
  84585. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84586. width = header[off_width];
  84587. height = header[off_height];
  84588. for (mip = 0; mip < mipmapCount; ++mip) {
  84589. if (lodIndex === -1 || lodIndex === mip) {
  84590. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84591. var i = (lodIndex === -1) ? mip : 0;
  84592. if (!info.isCompressed && info.isFourCC) {
  84593. dataLength = width * height * 4;
  84594. var floatArray = null;
  84595. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84596. if (bpp === 128) {
  84597. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84598. if (sphericalPolynomialFaces && i == 0) {
  84599. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84600. }
  84601. }
  84602. else if (bpp === 64) {
  84603. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84604. if (sphericalPolynomialFaces && i == 0) {
  84605. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84606. }
  84607. }
  84608. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84609. format = engine._getWebGLTextureType(info.textureType);
  84610. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84611. }
  84612. else {
  84613. if (bpp === 128) {
  84614. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84615. if (sphericalPolynomialFaces && i == 0) {
  84616. sphericalPolynomialFaces.push(floatArray);
  84617. }
  84618. }
  84619. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84620. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84621. if (sphericalPolynomialFaces && i == 0) {
  84622. sphericalPolynomialFaces.push(floatArray);
  84623. }
  84624. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84625. format = engine._getWebGLTextureType(info.textureType);
  84626. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84627. }
  84628. else { // 64
  84629. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84630. if (sphericalPolynomialFaces && i == 0) {
  84631. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84632. }
  84633. }
  84634. }
  84635. if (floatArray) {
  84636. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84637. }
  84638. }
  84639. else if (info.isRGB) {
  84640. if (bpp === 24) {
  84641. dataLength = width * height * 3;
  84642. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84643. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84644. }
  84645. else { // 32
  84646. dataLength = width * height * 4;
  84647. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84648. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84649. }
  84650. }
  84651. else if (info.isLuminance) {
  84652. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84653. var unpaddedRowSize = width;
  84654. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84655. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84656. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84657. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84658. }
  84659. else {
  84660. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84661. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84662. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84663. }
  84664. }
  84665. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84666. width *= 0.5;
  84667. height *= 0.5;
  84668. width = Math.max(1.0, width);
  84669. height = Math.max(1.0, height);
  84670. }
  84671. if (currentFace !== undefined) {
  84672. // Loading a single face
  84673. break;
  84674. }
  84675. }
  84676. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84677. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84678. size: header[off_width],
  84679. right: sphericalPolynomialFaces[0],
  84680. left: sphericalPolynomialFaces[1],
  84681. up: sphericalPolynomialFaces[2],
  84682. down: sphericalPolynomialFaces[3],
  84683. front: sphericalPolynomialFaces[4],
  84684. back: sphericalPolynomialFaces[5],
  84685. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84686. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84687. gammaSpace: false,
  84688. });
  84689. }
  84690. else {
  84691. info.sphericalPolynomial = undefined;
  84692. }
  84693. };
  84694. DDSTools.StoreLODInAlphaChannel = false;
  84695. return DDSTools;
  84696. }());
  84697. BABYLON.DDSTools = DDSTools;
  84698. })(BABYLON || (BABYLON = {}));
  84699. //# sourceMappingURL=babylon.dds.js.map
  84700. var BABYLON;
  84701. (function (BABYLON) {
  84702. /**
  84703. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84704. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84705. */
  84706. var KhronosTextureContainer = /** @class */ (function () {
  84707. /**
  84708. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84709. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84710. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84711. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84712. */
  84713. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84714. this.arrayBuffer = arrayBuffer;
  84715. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84716. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84717. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84718. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84719. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84720. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84721. BABYLON.Tools.Error("texture missing KTX identifier");
  84722. return;
  84723. }
  84724. // load the reset of the header in native 32 bit int
  84725. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84726. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84727. var oppositeEndianess = header[0] === 0x01020304;
  84728. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84729. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84730. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84731. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84732. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84733. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84734. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84735. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84736. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84737. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84738. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84739. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84740. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84741. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84742. if (this.glType !== 0) {
  84743. BABYLON.Tools.Error("only compressed formats currently supported");
  84744. return;
  84745. }
  84746. else {
  84747. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84748. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84749. }
  84750. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84751. BABYLON.Tools.Error("only 2D textures currently supported");
  84752. return;
  84753. }
  84754. if (this.numberOfArrayElements !== 0) {
  84755. BABYLON.Tools.Error("texture arrays not currently supported");
  84756. return;
  84757. }
  84758. if (this.numberOfFaces !== facesExpected) {
  84759. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84760. return;
  84761. }
  84762. // we now have a completely validated file, so could use existence of loadType as success
  84763. // would need to make this more elaborate & adjust checks above to support more than one load type
  84764. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84765. }
  84766. // not as fast hardware based, but will probably never need to use
  84767. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84768. return ((val & 0xFF) << 24)
  84769. | ((val & 0xFF00) << 8)
  84770. | ((val >> 8) & 0xFF00)
  84771. | ((val >> 24) & 0xFF);
  84772. };
  84773. /**
  84774. * It is assumed that the texture has already been created & is currently bound
  84775. */
  84776. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84777. switch (this.loadType) {
  84778. case KhronosTextureContainer.COMPRESSED_2D:
  84779. this._upload2DCompressedLevels(gl, loadMipmaps);
  84780. break;
  84781. case KhronosTextureContainer.TEX_2D:
  84782. case KhronosTextureContainer.COMPRESSED_3D:
  84783. case KhronosTextureContainer.TEX_3D:
  84784. }
  84785. };
  84786. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84787. // initialize width & height for level 1
  84788. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84789. var width = this.pixelWidth;
  84790. var height = this.pixelHeight;
  84791. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84792. for (var level = 0; level < mipmapCount; level++) {
  84793. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84794. for (var face = 0; face < this.numberOfFaces; face++) {
  84795. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84796. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84797. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84798. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84799. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84800. }
  84801. width = Math.max(1.0, width * 0.5);
  84802. height = Math.max(1.0, height * 0.5);
  84803. }
  84804. };
  84805. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84806. // load types
  84807. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84808. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84809. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84810. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84811. return KhronosTextureContainer;
  84812. }());
  84813. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84814. })(BABYLON || (BABYLON = {}));
  84815. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84816. var BABYLON;
  84817. (function (BABYLON) {
  84818. var Debug;
  84819. (function (Debug) {
  84820. /**
  84821. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84822. */
  84823. var SkeletonViewer = /** @class */ (function () {
  84824. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84825. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84826. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84827. this.skeleton = skeleton;
  84828. this.mesh = mesh;
  84829. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84830. this.renderingGroupId = renderingGroupId;
  84831. this.color = BABYLON.Color3.White();
  84832. this._debugLines = new Array();
  84833. this._isEnabled = false;
  84834. this._scene = scene;
  84835. this.update();
  84836. this._renderFunction = this.update.bind(this);
  84837. }
  84838. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84839. get: function () {
  84840. return this._isEnabled;
  84841. },
  84842. set: function (value) {
  84843. if (this._isEnabled === value) {
  84844. return;
  84845. }
  84846. this._isEnabled = value;
  84847. if (value) {
  84848. this._scene.registerBeforeRender(this._renderFunction);
  84849. }
  84850. else {
  84851. this._scene.unregisterBeforeRender(this._renderFunction);
  84852. }
  84853. },
  84854. enumerable: true,
  84855. configurable: true
  84856. });
  84857. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84858. if (x === void 0) { x = 0; }
  84859. if (y === void 0) { y = 0; }
  84860. if (z === void 0) { z = 0; }
  84861. var tmat = BABYLON.Tmp.Matrix[0];
  84862. var parentBone = bone.getParent();
  84863. tmat.copyFrom(bone.getLocalMatrix());
  84864. if (x !== 0 || y !== 0 || z !== 0) {
  84865. var tmat2 = BABYLON.Tmp.Matrix[1];
  84866. BABYLON.Matrix.IdentityToRef(tmat2);
  84867. tmat2.m[12] = x;
  84868. tmat2.m[13] = y;
  84869. tmat2.m[14] = z;
  84870. tmat2.multiplyToRef(tmat, tmat);
  84871. }
  84872. if (parentBone) {
  84873. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84874. }
  84875. tmat.multiplyToRef(meshMat, tmat);
  84876. position.x = tmat.m[12];
  84877. position.y = tmat.m[13];
  84878. position.z = tmat.m[14];
  84879. };
  84880. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84881. var len = bones.length;
  84882. var meshPos = this.mesh.position;
  84883. for (var i = 0; i < len; i++) {
  84884. var bone = bones[i];
  84885. var points = this._debugLines[i];
  84886. if (!points) {
  84887. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84888. this._debugLines[i] = points;
  84889. }
  84890. this._getBonePosition(points[0], bone, meshMat);
  84891. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84892. points[0].subtractInPlace(meshPos);
  84893. points[1].subtractInPlace(meshPos);
  84894. }
  84895. };
  84896. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84897. var len = bones.length;
  84898. var boneNum = 0;
  84899. var meshPos = this.mesh.position;
  84900. for (var i = len - 1; i >= 0; i--) {
  84901. var childBone = bones[i];
  84902. var parentBone = childBone.getParent();
  84903. if (!parentBone) {
  84904. continue;
  84905. }
  84906. var points = this._debugLines[boneNum];
  84907. if (!points) {
  84908. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84909. this._debugLines[boneNum] = points;
  84910. }
  84911. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84912. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84913. points[0].subtractInPlace(meshPos);
  84914. points[1].subtractInPlace(meshPos);
  84915. boneNum++;
  84916. }
  84917. };
  84918. SkeletonViewer.prototype.update = function () {
  84919. if (this.autoUpdateBonesMatrices) {
  84920. this.skeleton.computeAbsoluteTransforms();
  84921. }
  84922. if (this.skeleton.bones[0].length === undefined) {
  84923. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84924. }
  84925. else {
  84926. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84927. }
  84928. if (!this._debugMesh) {
  84929. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84930. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84931. }
  84932. else {
  84933. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84934. }
  84935. this._debugMesh.position.copyFrom(this.mesh.position);
  84936. this._debugMesh.color = this.color;
  84937. };
  84938. SkeletonViewer.prototype.dispose = function () {
  84939. if (this._debugMesh) {
  84940. this.isEnabled = false;
  84941. this._debugMesh.dispose();
  84942. this._debugMesh = null;
  84943. }
  84944. };
  84945. return SkeletonViewer;
  84946. }());
  84947. Debug.SkeletonViewer = SkeletonViewer;
  84948. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84949. })(BABYLON || (BABYLON = {}));
  84950. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84951. /**
  84952. * Module Debug contains the (visual) components to debug a scene correctly
  84953. */
  84954. var BABYLON;
  84955. (function (BABYLON) {
  84956. var Debug;
  84957. (function (Debug) {
  84958. /**
  84959. * The Axes viewer will show 3 axes in a specific point in space
  84960. */
  84961. var AxesViewer = /** @class */ (function () {
  84962. function AxesViewer(scene, scaleLines) {
  84963. if (scaleLines === void 0) { scaleLines = 1; }
  84964. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84965. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84966. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84967. this.scaleLines = 1;
  84968. this.scaleLines = scaleLines;
  84969. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84970. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84971. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84972. this._xmesh.renderingGroupId = 2;
  84973. this._ymesh.renderingGroupId = 2;
  84974. this._zmesh.renderingGroupId = 2;
  84975. this._xmesh.material.checkReadyOnlyOnce = true;
  84976. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84977. this._ymesh.material.checkReadyOnlyOnce = true;
  84978. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84979. this._zmesh.material.checkReadyOnlyOnce = true;
  84980. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84981. this.scene = scene;
  84982. }
  84983. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84984. var scaleLines = this.scaleLines;
  84985. if (this._xmesh) {
  84986. this._xmesh.position.copyFrom(position);
  84987. }
  84988. if (this._ymesh) {
  84989. this._ymesh.position.copyFrom(position);
  84990. }
  84991. if (this._zmesh) {
  84992. this._zmesh.position.copyFrom(position);
  84993. }
  84994. var point2 = this._xline[1];
  84995. point2.x = xaxis.x * scaleLines;
  84996. point2.y = xaxis.y * scaleLines;
  84997. point2.z = xaxis.z * scaleLines;
  84998. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84999. point2 = this._yline[1];
  85000. point2.x = yaxis.x * scaleLines;
  85001. point2.y = yaxis.y * scaleLines;
  85002. point2.z = yaxis.z * scaleLines;
  85003. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85004. point2 = this._zline[1];
  85005. point2.x = zaxis.x * scaleLines;
  85006. point2.y = zaxis.y * scaleLines;
  85007. point2.z = zaxis.z * scaleLines;
  85008. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85009. };
  85010. AxesViewer.prototype.dispose = function () {
  85011. if (this._xmesh) {
  85012. this._xmesh.dispose();
  85013. }
  85014. if (this._ymesh) {
  85015. this._ymesh.dispose();
  85016. }
  85017. if (this._zmesh) {
  85018. this._zmesh.dispose();
  85019. }
  85020. this._xmesh = null;
  85021. this._ymesh = null;
  85022. this._zmesh = null;
  85023. this.scene = null;
  85024. };
  85025. return AxesViewer;
  85026. }());
  85027. Debug.AxesViewer = AxesViewer;
  85028. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85029. })(BABYLON || (BABYLON = {}));
  85030. //# sourceMappingURL=babylon.axesViewer.js.map
  85031. var BABYLON;
  85032. (function (BABYLON) {
  85033. var Debug;
  85034. (function (Debug) {
  85035. /**
  85036. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85037. */
  85038. var BoneAxesViewer = /** @class */ (function (_super) {
  85039. __extends(BoneAxesViewer, _super);
  85040. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85041. if (scaleLines === void 0) { scaleLines = 1; }
  85042. var _this = _super.call(this, scene, scaleLines) || this;
  85043. _this.pos = BABYLON.Vector3.Zero();
  85044. _this.xaxis = BABYLON.Vector3.Zero();
  85045. _this.yaxis = BABYLON.Vector3.Zero();
  85046. _this.zaxis = BABYLON.Vector3.Zero();
  85047. _this.mesh = mesh;
  85048. _this.bone = bone;
  85049. return _this;
  85050. }
  85051. BoneAxesViewer.prototype.update = function () {
  85052. if (!this.mesh || !this.bone) {
  85053. return;
  85054. }
  85055. var bone = this.bone;
  85056. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85057. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85058. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85059. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85060. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85061. };
  85062. BoneAxesViewer.prototype.dispose = function () {
  85063. if (this.mesh) {
  85064. this.mesh = null;
  85065. this.bone = null;
  85066. _super.prototype.dispose.call(this);
  85067. }
  85068. };
  85069. return BoneAxesViewer;
  85070. }(Debug.AxesViewer));
  85071. Debug.BoneAxesViewer = BoneAxesViewer;
  85072. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85073. })(BABYLON || (BABYLON = {}));
  85074. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85075. var BABYLON;
  85076. (function (BABYLON) {
  85077. var RayHelper = /** @class */ (function () {
  85078. function RayHelper(ray) {
  85079. this.ray = ray;
  85080. }
  85081. RayHelper.CreateAndShow = function (ray, scene, color) {
  85082. var helper = new RayHelper(ray);
  85083. helper.show(scene, color);
  85084. return helper;
  85085. };
  85086. RayHelper.prototype.show = function (scene, color) {
  85087. if (!this._renderFunction && this.ray) {
  85088. var ray = this.ray;
  85089. this._renderFunction = this._render.bind(this);
  85090. this._scene = scene;
  85091. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85092. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85093. if (this._renderFunction) {
  85094. this._scene.registerBeforeRender(this._renderFunction);
  85095. }
  85096. }
  85097. if (color && this._renderLine) {
  85098. this._renderLine.color.copyFrom(color);
  85099. }
  85100. };
  85101. RayHelper.prototype.hide = function () {
  85102. if (this._renderFunction && this._scene) {
  85103. this._scene.unregisterBeforeRender(this._renderFunction);
  85104. this._scene = null;
  85105. this._renderFunction = null;
  85106. if (this._renderLine) {
  85107. this._renderLine.dispose();
  85108. this._renderLine = null;
  85109. }
  85110. this._renderPoints = [];
  85111. }
  85112. };
  85113. RayHelper.prototype._render = function () {
  85114. var ray = this.ray;
  85115. if (!ray) {
  85116. return;
  85117. }
  85118. var point = this._renderPoints[1];
  85119. var len = Math.min(ray.length, 1000000);
  85120. point.copyFrom(ray.direction);
  85121. point.scaleInPlace(len);
  85122. point.addInPlace(ray.origin);
  85123. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85124. };
  85125. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85126. this._attachedToMesh = mesh;
  85127. var ray = this.ray;
  85128. if (!ray) {
  85129. return;
  85130. }
  85131. if (!ray.direction) {
  85132. ray.direction = BABYLON.Vector3.Zero();
  85133. }
  85134. if (!ray.origin) {
  85135. ray.origin = BABYLON.Vector3.Zero();
  85136. }
  85137. if (length) {
  85138. ray.length = length;
  85139. }
  85140. if (!meshSpaceOrigin) {
  85141. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85142. }
  85143. if (!meshSpaceDirection) {
  85144. // -1 so that this will work with Mesh.lookAt
  85145. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85146. }
  85147. if (!this._meshSpaceDirection) {
  85148. this._meshSpaceDirection = meshSpaceDirection.clone();
  85149. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85150. }
  85151. else {
  85152. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85153. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85154. }
  85155. if (!this._updateToMeshFunction) {
  85156. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85157. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85158. }
  85159. this._updateToMesh();
  85160. };
  85161. RayHelper.prototype.detachFromMesh = function () {
  85162. if (this._attachedToMesh) {
  85163. if (this._updateToMeshFunction) {
  85164. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85165. }
  85166. this._attachedToMesh = null;
  85167. this._updateToMeshFunction = null;
  85168. }
  85169. };
  85170. RayHelper.prototype._updateToMesh = function () {
  85171. var ray = this.ray;
  85172. if (!this._attachedToMesh || !ray) {
  85173. return;
  85174. }
  85175. if (this._attachedToMesh._isDisposed) {
  85176. this.detachFromMesh();
  85177. return;
  85178. }
  85179. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85180. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85181. };
  85182. RayHelper.prototype.dispose = function () {
  85183. this.hide();
  85184. this.detachFromMesh();
  85185. this.ray = null;
  85186. };
  85187. return RayHelper;
  85188. }());
  85189. BABYLON.RayHelper = RayHelper;
  85190. })(BABYLON || (BABYLON = {}));
  85191. //# sourceMappingURL=babylon.rayHelper.js.map
  85192. var BABYLON;
  85193. (function (BABYLON) {
  85194. // load the inspector using require, if not present in the global namespace.
  85195. var DebugLayer = /** @class */ (function () {
  85196. function DebugLayer(scene) {
  85197. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85198. this._scene = scene;
  85199. // load inspector using require, if it doesn't exist on the global namespace.
  85200. }
  85201. /** Creates the inspector window. */
  85202. DebugLayer.prototype._createInspector = function (config) {
  85203. if (config === void 0) { config = {}; }
  85204. var popup = config.popup || false;
  85205. var initialTab = config.initialTab || 0;
  85206. var parentElement = config.parentElement || null;
  85207. if (!this._inspector) {
  85208. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85209. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85210. } // else nothing to do,; instance is already existing
  85211. };
  85212. DebugLayer.prototype.isVisible = function () {
  85213. if (!this._inspector) {
  85214. return false;
  85215. }
  85216. return true;
  85217. };
  85218. DebugLayer.prototype.hide = function () {
  85219. if (this._inspector) {
  85220. try {
  85221. this._inspector.dispose();
  85222. }
  85223. catch (e) {
  85224. // If the inspector has been removed directly from the inspector tool
  85225. }
  85226. this._inspector = null;
  85227. }
  85228. };
  85229. DebugLayer.prototype.show = function (config) {
  85230. if (config === void 0) { config = {}; }
  85231. if (typeof this.BJSINSPECTOR == 'undefined') {
  85232. // Load inspector and add it to the DOM
  85233. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85234. }
  85235. else {
  85236. // Otherwise creates the inspector
  85237. this._createInspector(config);
  85238. }
  85239. };
  85240. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85241. return DebugLayer;
  85242. }());
  85243. BABYLON.DebugLayer = DebugLayer;
  85244. })(BABYLON || (BABYLON = {}));
  85245. //# sourceMappingURL=babylon.debugLayer.js.map
  85246. var BABYLON;
  85247. (function (BABYLON) {
  85248. var Debug;
  85249. (function (Debug) {
  85250. /**
  85251. * Used to show the physics impostor around the specific mesh.
  85252. */
  85253. var PhysicsViewer = /** @class */ (function () {
  85254. function PhysicsViewer(scene) {
  85255. this._impostors = [];
  85256. this._meshes = [];
  85257. this._numMeshes = 0;
  85258. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85259. var physicEngine = this._scene.getPhysicsEngine();
  85260. if (physicEngine) {
  85261. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85262. }
  85263. }
  85264. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85265. var plugin = this._physicsEnginePlugin;
  85266. for (var i = 0; i < this._numMeshes; i++) {
  85267. var impostor = this._impostors[i];
  85268. if (!impostor) {
  85269. continue;
  85270. }
  85271. if (impostor.isDisposed) {
  85272. this.hideImpostor(this._impostors[i--]);
  85273. }
  85274. else {
  85275. var mesh = this._meshes[i];
  85276. if (mesh && plugin) {
  85277. plugin.syncMeshWithImpostor(mesh, impostor);
  85278. }
  85279. }
  85280. }
  85281. };
  85282. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85283. if (!this._scene) {
  85284. return;
  85285. }
  85286. for (var i = 0; i < this._numMeshes; i++) {
  85287. if (this._impostors[i] == impostor) {
  85288. return;
  85289. }
  85290. }
  85291. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85292. if (debugMesh) {
  85293. this._impostors[this._numMeshes] = impostor;
  85294. this._meshes[this._numMeshes] = debugMesh;
  85295. if (this._numMeshes === 0) {
  85296. this._renderFunction = this._updateDebugMeshes.bind(this);
  85297. this._scene.registerBeforeRender(this._renderFunction);
  85298. }
  85299. this._numMeshes++;
  85300. }
  85301. };
  85302. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85303. if (!impostor || !this._scene) {
  85304. return;
  85305. }
  85306. var removed = false;
  85307. for (var i = 0; i < this._numMeshes; i++) {
  85308. if (this._impostors[i] == impostor) {
  85309. var mesh = this._meshes[i];
  85310. if (!mesh) {
  85311. continue;
  85312. }
  85313. this._scene.removeMesh(mesh);
  85314. mesh.dispose();
  85315. this._numMeshes--;
  85316. if (this._numMeshes > 0) {
  85317. this._meshes[i] = this._meshes[this._numMeshes];
  85318. this._impostors[i] = this._impostors[this._numMeshes];
  85319. this._meshes[this._numMeshes] = null;
  85320. this._impostors[this._numMeshes] = null;
  85321. }
  85322. else {
  85323. this._meshes[0] = null;
  85324. this._impostors[0] = null;
  85325. }
  85326. removed = true;
  85327. break;
  85328. }
  85329. }
  85330. if (removed && this._numMeshes === 0) {
  85331. this._scene.unregisterBeforeRender(this._renderFunction);
  85332. }
  85333. };
  85334. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85335. if (!this._debugMaterial) {
  85336. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85337. this._debugMaterial.wireframe = true;
  85338. }
  85339. return this._debugMaterial;
  85340. };
  85341. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85342. if (!this._debugBoxMesh) {
  85343. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85344. this._debugBoxMesh.renderingGroupId = 1;
  85345. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85346. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85347. scene.removeMesh(this._debugBoxMesh);
  85348. }
  85349. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85350. };
  85351. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85352. if (!this._debugSphereMesh) {
  85353. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85354. this._debugSphereMesh.renderingGroupId = 1;
  85355. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85356. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85357. scene.removeMesh(this._debugSphereMesh);
  85358. }
  85359. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85360. };
  85361. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85362. var mesh = null;
  85363. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85364. mesh = this._getDebugBoxMesh(scene);
  85365. impostor.getBoxSizeToRef(mesh.scaling);
  85366. }
  85367. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85368. mesh = this._getDebugSphereMesh(scene);
  85369. var radius = impostor.getRadius();
  85370. mesh.scaling.x = radius * 2;
  85371. mesh.scaling.y = radius * 2;
  85372. mesh.scaling.z = radius * 2;
  85373. }
  85374. return mesh;
  85375. };
  85376. PhysicsViewer.prototype.dispose = function () {
  85377. for (var i = 0; i < this._numMeshes; i++) {
  85378. this.hideImpostor(this._impostors[i]);
  85379. }
  85380. if (this._debugBoxMesh) {
  85381. this._debugBoxMesh.dispose();
  85382. }
  85383. if (this._debugSphereMesh) {
  85384. this._debugSphereMesh.dispose();
  85385. }
  85386. if (this._debugMaterial) {
  85387. this._debugMaterial.dispose();
  85388. }
  85389. this._impostors.length = 0;
  85390. this._scene = null;
  85391. this._physicsEnginePlugin = null;
  85392. };
  85393. return PhysicsViewer;
  85394. }());
  85395. Debug.PhysicsViewer = PhysicsViewer;
  85396. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85397. })(BABYLON || (BABYLON = {}));
  85398. //# sourceMappingURL=babylon.physicsViewer.js.map
  85399. var BABYLON;
  85400. (function (BABYLON) {
  85401. var BoundingBoxRenderer = /** @class */ (function () {
  85402. function BoundingBoxRenderer(scene) {
  85403. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85404. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85405. this.showBackLines = true;
  85406. this.renderList = new BABYLON.SmartArray(32);
  85407. this._vertexBuffers = {};
  85408. this._scene = scene;
  85409. }
  85410. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85411. if (this._colorShader) {
  85412. return;
  85413. }
  85414. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85415. attributes: [BABYLON.VertexBuffer.PositionKind],
  85416. uniforms: ["world", "viewProjection", "color"]
  85417. });
  85418. var engine = this._scene.getEngine();
  85419. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85420. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85421. this._createIndexBuffer();
  85422. };
  85423. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85424. var engine = this._scene.getEngine();
  85425. 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]);
  85426. };
  85427. BoundingBoxRenderer.prototype._rebuild = function () {
  85428. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85429. if (vb) {
  85430. vb._rebuild();
  85431. }
  85432. this._createIndexBuffer();
  85433. };
  85434. BoundingBoxRenderer.prototype.reset = function () {
  85435. this.renderList.reset();
  85436. };
  85437. BoundingBoxRenderer.prototype.render = function () {
  85438. if (this.renderList.length === 0) {
  85439. return;
  85440. }
  85441. this._prepareRessources();
  85442. if (!this._colorShader.isReady()) {
  85443. return;
  85444. }
  85445. var engine = this._scene.getEngine();
  85446. engine.setDepthWrite(false);
  85447. this._colorShader._preBind();
  85448. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85449. var boundingBox = this.renderList.data[boundingBoxIndex];
  85450. var min = boundingBox.minimum;
  85451. var max = boundingBox.maximum;
  85452. var diff = max.subtract(min);
  85453. var median = min.add(diff.scale(0.5));
  85454. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85455. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85456. .multiply(boundingBox.getWorldMatrix());
  85457. // VBOs
  85458. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85459. if (this.showBackLines) {
  85460. // Back
  85461. engine.setDepthFunctionToGreaterOrEqual();
  85462. this._scene.resetCachedMaterial();
  85463. this._colorShader.setColor4("color", this.backColor.toColor4());
  85464. this._colorShader.bind(worldMatrix);
  85465. // Draw order
  85466. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85467. }
  85468. // Front
  85469. engine.setDepthFunctionToLess();
  85470. this._scene.resetCachedMaterial();
  85471. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85472. this._colorShader.bind(worldMatrix);
  85473. // Draw order
  85474. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85475. }
  85476. this._colorShader.unbind();
  85477. engine.setDepthFunctionToLessOrEqual();
  85478. engine.setDepthWrite(true);
  85479. };
  85480. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85481. this._prepareRessources();
  85482. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85483. return;
  85484. }
  85485. var engine = this._scene.getEngine();
  85486. engine.setDepthWrite(false);
  85487. engine.setColorWrite(false);
  85488. this._colorShader._preBind();
  85489. var boundingBox = mesh._boundingInfo.boundingBox;
  85490. var min = boundingBox.minimum;
  85491. var max = boundingBox.maximum;
  85492. var diff = max.subtract(min);
  85493. var median = min.add(diff.scale(0.5));
  85494. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85495. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85496. .multiply(boundingBox.getWorldMatrix());
  85497. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85498. engine.setDepthFunctionToLess();
  85499. this._scene.resetCachedMaterial();
  85500. this._colorShader.bind(worldMatrix);
  85501. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85502. this._colorShader.unbind();
  85503. engine.setDepthFunctionToLessOrEqual();
  85504. engine.setDepthWrite(true);
  85505. engine.setColorWrite(true);
  85506. };
  85507. BoundingBoxRenderer.prototype.dispose = function () {
  85508. if (!this._colorShader) {
  85509. return;
  85510. }
  85511. this.renderList.dispose();
  85512. this._colorShader.dispose();
  85513. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85514. if (buffer) {
  85515. buffer.dispose();
  85516. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85517. }
  85518. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85519. };
  85520. return BoundingBoxRenderer;
  85521. }());
  85522. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85523. })(BABYLON || (BABYLON = {}));
  85524. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85525. var BABYLON;
  85526. (function (BABYLON) {
  85527. /**
  85528. * Defines a target to use with MorphTargetManager
  85529. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85530. */
  85531. var MorphTarget = /** @class */ (function () {
  85532. /**
  85533. * Creates a new MorphTarget
  85534. * @param name defines the name of the target
  85535. * @param influence defines the influence to use
  85536. */
  85537. function MorphTarget(
  85538. /** defines the name of the target */
  85539. name, influence) {
  85540. if (influence === void 0) { influence = 0; }
  85541. this.name = name;
  85542. /**
  85543. * Gets or sets the list of animations
  85544. */
  85545. this.animations = new Array();
  85546. this._positions = null;
  85547. this._normals = null;
  85548. this._tangents = null;
  85549. /**
  85550. * Observable raised when the influence changes
  85551. */
  85552. this.onInfluenceChanged = new BABYLON.Observable();
  85553. this.influence = influence;
  85554. }
  85555. Object.defineProperty(MorphTarget.prototype, "influence", {
  85556. /**
  85557. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85558. */
  85559. get: function () {
  85560. return this._influence;
  85561. },
  85562. set: function (influence) {
  85563. if (this._influence === influence) {
  85564. return;
  85565. }
  85566. var previous = this._influence;
  85567. this._influence = influence;
  85568. if (this.onInfluenceChanged.hasObservers) {
  85569. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85570. }
  85571. },
  85572. enumerable: true,
  85573. configurable: true
  85574. });
  85575. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85576. /**
  85577. * Gets a boolean defining if the target contains position data
  85578. */
  85579. get: function () {
  85580. return !!this._positions;
  85581. },
  85582. enumerable: true,
  85583. configurable: true
  85584. });
  85585. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85586. /**
  85587. * Gets a boolean defining if the target contains normal data
  85588. */
  85589. get: function () {
  85590. return !!this._normals;
  85591. },
  85592. enumerable: true,
  85593. configurable: true
  85594. });
  85595. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85596. /**
  85597. * Gets a boolean defining if the target contains tangent data
  85598. */
  85599. get: function () {
  85600. return !!this._tangents;
  85601. },
  85602. enumerable: true,
  85603. configurable: true
  85604. });
  85605. /**
  85606. * Affects position data to this target
  85607. * @param data defines the position data to use
  85608. */
  85609. MorphTarget.prototype.setPositions = function (data) {
  85610. this._positions = data;
  85611. };
  85612. /**
  85613. * Gets the position data stored in this target
  85614. * @returns a FloatArray containing the position data (or null if not present)
  85615. */
  85616. MorphTarget.prototype.getPositions = function () {
  85617. return this._positions;
  85618. };
  85619. /**
  85620. * Affects normal data to this target
  85621. * @param data defines the normal data to use
  85622. */
  85623. MorphTarget.prototype.setNormals = function (data) {
  85624. this._normals = data;
  85625. };
  85626. /**
  85627. * Gets the normal data stored in this target
  85628. * @returns a FloatArray containing the normal data (or null if not present)
  85629. */
  85630. MorphTarget.prototype.getNormals = function () {
  85631. return this._normals;
  85632. };
  85633. /**
  85634. * Affects tangent data to this target
  85635. * @param data defines the tangent data to use
  85636. */
  85637. MorphTarget.prototype.setTangents = function (data) {
  85638. this._tangents = data;
  85639. };
  85640. /**
  85641. * Gets the tangent data stored in this target
  85642. * @returns a FloatArray containing the tangent data (or null if not present)
  85643. */
  85644. MorphTarget.prototype.getTangents = function () {
  85645. return this._tangents;
  85646. };
  85647. /**
  85648. * Serializes the current target into a Serialization object
  85649. * @returns the serialized object
  85650. */
  85651. MorphTarget.prototype.serialize = function () {
  85652. var serializationObject = {};
  85653. serializationObject.name = this.name;
  85654. serializationObject.influence = this.influence;
  85655. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85656. if (this.hasNormals) {
  85657. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85658. }
  85659. if (this.hasTangents) {
  85660. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85661. }
  85662. // Animations
  85663. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85664. return serializationObject;
  85665. };
  85666. // Statics
  85667. /**
  85668. * Creates a new target from serialized data
  85669. * @param serializationObject defines the serialized data to use
  85670. * @returns a new MorphTarget
  85671. */
  85672. MorphTarget.Parse = function (serializationObject) {
  85673. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85674. result.setPositions(serializationObject.positions);
  85675. if (serializationObject.normals) {
  85676. result.setNormals(serializationObject.normals);
  85677. }
  85678. if (serializationObject.tangents) {
  85679. result.setTangents(serializationObject.tangents);
  85680. }
  85681. // Animations
  85682. if (serializationObject.animations) {
  85683. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85684. var parsedAnimation = serializationObject.animations[animationIndex];
  85685. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85686. }
  85687. }
  85688. return result;
  85689. };
  85690. /**
  85691. * Creates a MorphTarget from mesh data
  85692. * @param mesh defines the source mesh
  85693. * @param name defines the name to use for the new target
  85694. * @param influence defines the influence to attach to the target
  85695. * @returns a new MorphTarget
  85696. */
  85697. MorphTarget.FromMesh = function (mesh, name, influence) {
  85698. if (!name) {
  85699. name = mesh.name;
  85700. }
  85701. var result = new MorphTarget(name, influence);
  85702. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85703. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85704. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85705. }
  85706. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85707. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85708. }
  85709. return result;
  85710. };
  85711. return MorphTarget;
  85712. }());
  85713. BABYLON.MorphTarget = MorphTarget;
  85714. })(BABYLON || (BABYLON = {}));
  85715. //# sourceMappingURL=babylon.morphTarget.js.map
  85716. var BABYLON;
  85717. (function (BABYLON) {
  85718. /**
  85719. * This class is used to deform meshes using morphing between different targets
  85720. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85721. */
  85722. var MorphTargetManager = /** @class */ (function () {
  85723. /**
  85724. * Creates a new MorphTargetManager
  85725. * @param scene defines the current scene
  85726. */
  85727. function MorphTargetManager(scene) {
  85728. if (scene === void 0) { scene = null; }
  85729. this._targets = new Array();
  85730. this._targetObservable = new Array();
  85731. this._activeTargets = new BABYLON.SmartArray(16);
  85732. this._supportsNormals = false;
  85733. this._supportsTangents = false;
  85734. this._vertexCount = 0;
  85735. this._uniqueId = 0;
  85736. this._tempInfluences = new Array();
  85737. if (!scene) {
  85738. scene = BABYLON.Engine.LastCreatedScene;
  85739. }
  85740. this._scene = scene;
  85741. if (this._scene) {
  85742. this._scene.morphTargetManagers.push(this);
  85743. this._uniqueId = this._scene.getUniqueId();
  85744. }
  85745. }
  85746. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85747. /**
  85748. * Gets the unique ID of this manager
  85749. */
  85750. get: function () {
  85751. return this._uniqueId;
  85752. },
  85753. enumerable: true,
  85754. configurable: true
  85755. });
  85756. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85757. /**
  85758. * Gets the number of vertices handled by this manager
  85759. */
  85760. get: function () {
  85761. return this._vertexCount;
  85762. },
  85763. enumerable: true,
  85764. configurable: true
  85765. });
  85766. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85767. /**
  85768. * Gets a boolean indicating if this manager supports morphing of normals
  85769. */
  85770. get: function () {
  85771. return this._supportsNormals;
  85772. },
  85773. enumerable: true,
  85774. configurable: true
  85775. });
  85776. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85777. /**
  85778. * Gets a boolean indicating if this manager supports morphing of tangents
  85779. */
  85780. get: function () {
  85781. return this._supportsTangents;
  85782. },
  85783. enumerable: true,
  85784. configurable: true
  85785. });
  85786. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85787. /**
  85788. * Gets the number of targets stored in this manager
  85789. */
  85790. get: function () {
  85791. return this._targets.length;
  85792. },
  85793. enumerable: true,
  85794. configurable: true
  85795. });
  85796. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85797. /**
  85798. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85799. */
  85800. get: function () {
  85801. return this._activeTargets.length;
  85802. },
  85803. enumerable: true,
  85804. configurable: true
  85805. });
  85806. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85807. /**
  85808. * Gets the list of influences (one per target)
  85809. */
  85810. get: function () {
  85811. return this._influences;
  85812. },
  85813. enumerable: true,
  85814. configurable: true
  85815. });
  85816. /**
  85817. * Gets the active target at specified index. An active target is a target with an influence > 0
  85818. * @param index defines the index to check
  85819. * @returns the requested target
  85820. */
  85821. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85822. return this._activeTargets.data[index];
  85823. };
  85824. /**
  85825. * Gets the target at specified index
  85826. * @param index defines the index to check
  85827. * @returns the requested target
  85828. */
  85829. MorphTargetManager.prototype.getTarget = function (index) {
  85830. return this._targets[index];
  85831. };
  85832. /**
  85833. * Add a new target to this manager
  85834. * @param target defines the target to add
  85835. */
  85836. MorphTargetManager.prototype.addTarget = function (target) {
  85837. var _this = this;
  85838. this._targets.push(target);
  85839. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85840. _this._syncActiveTargets(needUpdate);
  85841. }));
  85842. this._syncActiveTargets(true);
  85843. };
  85844. /**
  85845. * Removes a target from the manager
  85846. * @param target defines the target to remove
  85847. */
  85848. MorphTargetManager.prototype.removeTarget = function (target) {
  85849. var index = this._targets.indexOf(target);
  85850. if (index >= 0) {
  85851. this._targets.splice(index, 1);
  85852. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85853. this._syncActiveTargets(true);
  85854. }
  85855. };
  85856. /**
  85857. * Serializes the current manager into a Serialization object
  85858. * @returns the serialized object
  85859. */
  85860. MorphTargetManager.prototype.serialize = function () {
  85861. var serializationObject = {};
  85862. serializationObject.id = this.uniqueId;
  85863. serializationObject.targets = [];
  85864. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85865. var target = _a[_i];
  85866. serializationObject.targets.push(target.serialize());
  85867. }
  85868. return serializationObject;
  85869. };
  85870. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85871. var influenceCount = 0;
  85872. this._activeTargets.reset();
  85873. this._supportsNormals = true;
  85874. this._supportsTangents = true;
  85875. this._vertexCount = 0;
  85876. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85877. var target = _a[_i];
  85878. this._activeTargets.push(target);
  85879. this._tempInfluences[influenceCount++] = target.influence;
  85880. var positions = target.getPositions();
  85881. if (positions) {
  85882. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85883. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85884. var vertexCount = positions.length / 3;
  85885. if (this._vertexCount === 0) {
  85886. this._vertexCount = vertexCount;
  85887. }
  85888. else if (this._vertexCount !== vertexCount) {
  85889. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85890. return;
  85891. }
  85892. }
  85893. }
  85894. if (!this._influences || this._influences.length !== influenceCount) {
  85895. this._influences = new Float32Array(influenceCount);
  85896. }
  85897. for (var index = 0; index < influenceCount; index++) {
  85898. this._influences[index] = this._tempInfluences[index];
  85899. }
  85900. if (needUpdate) {
  85901. this.synchronize();
  85902. }
  85903. };
  85904. /**
  85905. * Syncrhonize the targets with all the meshes using this morph target manager
  85906. */
  85907. MorphTargetManager.prototype.synchronize = function () {
  85908. if (!this._scene) {
  85909. return;
  85910. }
  85911. // Flag meshes as dirty to resync with the active targets
  85912. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85913. var mesh = _a[_i];
  85914. if (mesh.morphTargetManager === this) {
  85915. mesh._syncGeometryWithMorphTargetManager();
  85916. }
  85917. }
  85918. };
  85919. // Statics
  85920. /**
  85921. * Creates a new MorphTargetManager from serialized data
  85922. * @param serializationObject defines the serialized data
  85923. * @param scene defines the hosting scene
  85924. * @returns the new MorphTargetManager
  85925. */
  85926. MorphTargetManager.Parse = function (serializationObject, scene) {
  85927. var result = new MorphTargetManager(scene);
  85928. result._uniqueId = serializationObject.id;
  85929. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85930. var targetData = _a[_i];
  85931. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85932. }
  85933. return result;
  85934. };
  85935. return MorphTargetManager;
  85936. }());
  85937. BABYLON.MorphTargetManager = MorphTargetManager;
  85938. })(BABYLON || (BABYLON = {}));
  85939. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85940. var BABYLON;
  85941. (function (BABYLON) {
  85942. var Octree = /** @class */ (function () {
  85943. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85944. if (maxDepth === void 0) { maxDepth = 2; }
  85945. this.maxDepth = maxDepth;
  85946. this.dynamicContent = new Array();
  85947. this._maxBlockCapacity = maxBlockCapacity || 64;
  85948. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85949. this._creationFunc = creationFunc;
  85950. }
  85951. // Methods
  85952. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85953. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85954. };
  85955. Octree.prototype.addMesh = function (entry) {
  85956. for (var index = 0; index < this.blocks.length; index++) {
  85957. var block = this.blocks[index];
  85958. block.addEntry(entry);
  85959. }
  85960. };
  85961. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85962. this._selectionContent.reset();
  85963. for (var index = 0; index < this.blocks.length; index++) {
  85964. var block = this.blocks[index];
  85965. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85966. }
  85967. if (allowDuplicate) {
  85968. this._selectionContent.concat(this.dynamicContent);
  85969. }
  85970. else {
  85971. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85972. }
  85973. return this._selectionContent;
  85974. };
  85975. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85976. this._selectionContent.reset();
  85977. for (var index = 0; index < this.blocks.length; index++) {
  85978. var block = this.blocks[index];
  85979. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85980. }
  85981. if (allowDuplicate) {
  85982. this._selectionContent.concat(this.dynamicContent);
  85983. }
  85984. else {
  85985. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85986. }
  85987. return this._selectionContent;
  85988. };
  85989. Octree.prototype.intersectsRay = function (ray) {
  85990. this._selectionContent.reset();
  85991. for (var index = 0; index < this.blocks.length; index++) {
  85992. var block = this.blocks[index];
  85993. block.intersectsRay(ray, this._selectionContent);
  85994. }
  85995. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85996. return this._selectionContent;
  85997. };
  85998. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85999. target.blocks = new Array();
  86000. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86001. // Segmenting space
  86002. for (var x = 0; x < 2; x++) {
  86003. for (var y = 0; y < 2; y++) {
  86004. for (var z = 0; z < 2; z++) {
  86005. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86006. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86007. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86008. block.addEntries(entries);
  86009. target.blocks.push(block);
  86010. }
  86011. }
  86012. }
  86013. };
  86014. Octree.CreationFuncForMeshes = function (entry, block) {
  86015. var boundingInfo = entry.getBoundingInfo();
  86016. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86017. block.entries.push(entry);
  86018. }
  86019. };
  86020. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86021. var boundingInfo = entry.getBoundingInfo();
  86022. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86023. block.entries.push(entry);
  86024. }
  86025. };
  86026. return Octree;
  86027. }());
  86028. BABYLON.Octree = Octree;
  86029. })(BABYLON || (BABYLON = {}));
  86030. //# sourceMappingURL=babylon.octree.js.map
  86031. var BABYLON;
  86032. (function (BABYLON) {
  86033. var OctreeBlock = /** @class */ (function () {
  86034. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86035. this.entries = new Array();
  86036. this._boundingVectors = new Array();
  86037. this._capacity = capacity;
  86038. this._depth = depth;
  86039. this._maxDepth = maxDepth;
  86040. this._creationFunc = creationFunc;
  86041. this._minPoint = minPoint;
  86042. this._maxPoint = maxPoint;
  86043. this._boundingVectors.push(minPoint.clone());
  86044. this._boundingVectors.push(maxPoint.clone());
  86045. this._boundingVectors.push(minPoint.clone());
  86046. this._boundingVectors[2].x = maxPoint.x;
  86047. this._boundingVectors.push(minPoint.clone());
  86048. this._boundingVectors[3].y = maxPoint.y;
  86049. this._boundingVectors.push(minPoint.clone());
  86050. this._boundingVectors[4].z = maxPoint.z;
  86051. this._boundingVectors.push(maxPoint.clone());
  86052. this._boundingVectors[5].z = minPoint.z;
  86053. this._boundingVectors.push(maxPoint.clone());
  86054. this._boundingVectors[6].x = minPoint.x;
  86055. this._boundingVectors.push(maxPoint.clone());
  86056. this._boundingVectors[7].y = minPoint.y;
  86057. }
  86058. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86059. // Property
  86060. get: function () {
  86061. return this._capacity;
  86062. },
  86063. enumerable: true,
  86064. configurable: true
  86065. });
  86066. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86067. get: function () {
  86068. return this._minPoint;
  86069. },
  86070. enumerable: true,
  86071. configurable: true
  86072. });
  86073. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86074. get: function () {
  86075. return this._maxPoint;
  86076. },
  86077. enumerable: true,
  86078. configurable: true
  86079. });
  86080. // Methods
  86081. OctreeBlock.prototype.addEntry = function (entry) {
  86082. if (this.blocks) {
  86083. for (var index = 0; index < this.blocks.length; index++) {
  86084. var block = this.blocks[index];
  86085. block.addEntry(entry);
  86086. }
  86087. return;
  86088. }
  86089. this._creationFunc(entry, this);
  86090. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86091. this.createInnerBlocks();
  86092. }
  86093. };
  86094. OctreeBlock.prototype.addEntries = function (entries) {
  86095. for (var index = 0; index < entries.length; index++) {
  86096. var mesh = entries[index];
  86097. this.addEntry(mesh);
  86098. }
  86099. };
  86100. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86101. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86102. if (this.blocks) {
  86103. for (var index = 0; index < this.blocks.length; index++) {
  86104. var block = this.blocks[index];
  86105. block.select(frustumPlanes, selection, allowDuplicate);
  86106. }
  86107. return;
  86108. }
  86109. if (allowDuplicate) {
  86110. selection.concat(this.entries);
  86111. }
  86112. else {
  86113. selection.concatWithNoDuplicate(this.entries);
  86114. }
  86115. }
  86116. };
  86117. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86118. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86119. if (this.blocks) {
  86120. for (var index = 0; index < this.blocks.length; index++) {
  86121. var block = this.blocks[index];
  86122. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86123. }
  86124. return;
  86125. }
  86126. if (allowDuplicate) {
  86127. selection.concat(this.entries);
  86128. }
  86129. else {
  86130. selection.concatWithNoDuplicate(this.entries);
  86131. }
  86132. }
  86133. };
  86134. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86135. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86136. if (this.blocks) {
  86137. for (var index = 0; index < this.blocks.length; index++) {
  86138. var block = this.blocks[index];
  86139. block.intersectsRay(ray, selection);
  86140. }
  86141. return;
  86142. }
  86143. selection.concatWithNoDuplicate(this.entries);
  86144. }
  86145. };
  86146. OctreeBlock.prototype.createInnerBlocks = function () {
  86147. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86148. };
  86149. return OctreeBlock;
  86150. }());
  86151. BABYLON.OctreeBlock = OctreeBlock;
  86152. })(BABYLON || (BABYLON = {}));
  86153. //# sourceMappingURL=babylon.octreeBlock.js.map
  86154. var BABYLON;
  86155. (function (BABYLON) {
  86156. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86157. __extends(VRDistortionCorrectionPostProcess, _super);
  86158. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86159. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86160. 'LensCenter',
  86161. 'Scale',
  86162. 'ScaleIn',
  86163. 'HmdWarpParam'
  86164. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86165. _this._isRightEye = isRightEye;
  86166. _this._distortionFactors = vrMetrics.distortionK;
  86167. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86168. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86169. _this.adaptScaleToCurrentViewport = true;
  86170. _this.onSizeChangedObservable.add(function () {
  86171. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86172. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86173. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86174. });
  86175. _this.onApplyObservable.add(function (effect) {
  86176. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86177. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86178. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86179. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86180. });
  86181. return _this;
  86182. }
  86183. return VRDistortionCorrectionPostProcess;
  86184. }(BABYLON.PostProcess));
  86185. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86186. })(BABYLON || (BABYLON = {}));
  86187. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86188. var BABYLON;
  86189. (function (BABYLON) {
  86190. /**
  86191. * Postprocess used to generate anaglyphic rendering
  86192. */
  86193. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86194. __extends(AnaglyphPostProcess, _super);
  86195. /**
  86196. * Creates a new AnaglyphPostProcess
  86197. * @param name defines postprocess name
  86198. * @param options defines creation options or target ratio scale
  86199. * @param rigCameras defines cameras using this postprocess
  86200. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86201. * @param engine defines hosting engine
  86202. * @param reusable defines if the postprocess will be reused multiple times per frame
  86203. */
  86204. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86205. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86206. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86207. _this.onApplyObservable.add(function (effect) {
  86208. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86209. });
  86210. return _this;
  86211. }
  86212. return AnaglyphPostProcess;
  86213. }(BABYLON.PostProcess));
  86214. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86215. })(BABYLON || (BABYLON = {}));
  86216. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86217. var BABYLON;
  86218. (function (BABYLON) {
  86219. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86220. __extends(StereoscopicInterlacePostProcess, _super);
  86221. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86222. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86223. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86224. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86225. _this.onSizeChangedObservable.add(function () {
  86226. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86227. });
  86228. _this.onApplyObservable.add(function (effect) {
  86229. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86230. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86231. });
  86232. return _this;
  86233. }
  86234. return StereoscopicInterlacePostProcess;
  86235. }(BABYLON.PostProcess));
  86236. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86237. })(BABYLON || (BABYLON = {}));
  86238. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86239. var BABYLON;
  86240. (function (BABYLON) {
  86241. /**
  86242. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86243. * Screen rotation is taken into account.
  86244. */
  86245. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86246. function FreeCameraDeviceOrientationInput() {
  86247. var _this = this;
  86248. this._screenOrientationAngle = 0;
  86249. this._screenQuaternion = new BABYLON.Quaternion();
  86250. this._alpha = 0;
  86251. this._beta = 0;
  86252. this._gamma = 0;
  86253. this._orientationChanged = function () {
  86254. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86255. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86256. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86257. };
  86258. this._deviceOrientation = function (evt) {
  86259. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86260. _this._beta = evt.beta !== null ? evt.beta : 0;
  86261. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86262. };
  86263. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86264. this._orientationChanged();
  86265. }
  86266. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86267. get: function () {
  86268. return this._camera;
  86269. },
  86270. set: function (camera) {
  86271. this._camera = camera;
  86272. if (this._camera != null && !this._camera.rotationQuaternion) {
  86273. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86274. }
  86275. },
  86276. enumerable: true,
  86277. configurable: true
  86278. });
  86279. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86280. window.addEventListener("orientationchange", this._orientationChanged);
  86281. window.addEventListener("deviceorientation", this._deviceOrientation);
  86282. //In certain cases, the attach control is called AFTER orientation was changed,
  86283. //So this is needed.
  86284. this._orientationChanged();
  86285. };
  86286. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86287. window.removeEventListener("orientationchange", this._orientationChanged);
  86288. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86289. };
  86290. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86291. //if no device orientation provided, don't update the rotation.
  86292. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86293. if (!this._alpha)
  86294. return;
  86295. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86296. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86297. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86298. //Mirror on XY Plane
  86299. this._camera.rotationQuaternion.z *= -1;
  86300. this._camera.rotationQuaternion.w *= -1;
  86301. };
  86302. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86303. return "FreeCameraDeviceOrientationInput";
  86304. };
  86305. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86306. return "deviceOrientation";
  86307. };
  86308. return FreeCameraDeviceOrientationInput;
  86309. }());
  86310. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86311. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86312. })(BABYLON || (BABYLON = {}));
  86313. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86314. var BABYLON;
  86315. (function (BABYLON) {
  86316. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86317. function ArcRotateCameraVRDeviceOrientationInput() {
  86318. this.alphaCorrection = 1;
  86319. this.betaCorrection = 1;
  86320. this.gammaCorrection = 1;
  86321. this._alpha = 0;
  86322. this._gamma = 0;
  86323. this._dirty = false;
  86324. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86325. }
  86326. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86327. this.camera.attachControl(element, noPreventDefault);
  86328. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86329. };
  86330. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86331. if (evt.alpha !== null) {
  86332. this._alpha = +evt.alpha | 0;
  86333. }
  86334. if (evt.gamma !== null) {
  86335. this._gamma = +evt.gamma | 0;
  86336. }
  86337. this._dirty = true;
  86338. };
  86339. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86340. if (this._dirty) {
  86341. this._dirty = false;
  86342. if (this._gamma < 0) {
  86343. this._gamma = 180 + this._gamma;
  86344. }
  86345. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86346. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86347. }
  86348. };
  86349. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86350. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86351. };
  86352. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86353. return "ArcRotateCameraVRDeviceOrientationInput";
  86354. };
  86355. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86356. return "VRDeviceOrientation";
  86357. };
  86358. return ArcRotateCameraVRDeviceOrientationInput;
  86359. }());
  86360. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86361. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86362. })(BABYLON || (BABYLON = {}));
  86363. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86364. var BABYLON;
  86365. (function (BABYLON) {
  86366. var VRCameraMetrics = /** @class */ (function () {
  86367. function VRCameraMetrics() {
  86368. this.compensateDistortion = true;
  86369. }
  86370. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86371. get: function () {
  86372. return this.hResolution / (2 * this.vResolution);
  86373. },
  86374. enumerable: true,
  86375. configurable: true
  86376. });
  86377. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86378. get: function () {
  86379. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86380. },
  86381. enumerable: true,
  86382. configurable: true
  86383. });
  86384. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86385. get: function () {
  86386. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86387. var h = (4 * meters) / this.hScreenSize;
  86388. return BABYLON.Matrix.Translation(h, 0, 0);
  86389. },
  86390. enumerable: true,
  86391. configurable: true
  86392. });
  86393. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86394. get: function () {
  86395. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86396. var h = (4 * meters) / this.hScreenSize;
  86397. return BABYLON.Matrix.Translation(-h, 0, 0);
  86398. },
  86399. enumerable: true,
  86400. configurable: true
  86401. });
  86402. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86403. get: function () {
  86404. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86405. },
  86406. enumerable: true,
  86407. configurable: true
  86408. });
  86409. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86410. get: function () {
  86411. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86412. },
  86413. enumerable: true,
  86414. configurable: true
  86415. });
  86416. VRCameraMetrics.GetDefault = function () {
  86417. var result = new VRCameraMetrics();
  86418. result.hResolution = 1280;
  86419. result.vResolution = 800;
  86420. result.hScreenSize = 0.149759993;
  86421. result.vScreenSize = 0.0935999975;
  86422. result.vScreenCenter = 0.0467999987;
  86423. result.eyeToScreenDistance = 0.0410000011;
  86424. result.lensSeparationDistance = 0.0635000020;
  86425. result.interpupillaryDistance = 0.0640000030;
  86426. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86427. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86428. result.postProcessScaleFactor = 1.714605507808412;
  86429. result.lensCenterOffset = 0.151976421;
  86430. return result;
  86431. };
  86432. return VRCameraMetrics;
  86433. }());
  86434. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86435. })(BABYLON || (BABYLON = {}));
  86436. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86437. var BABYLON;
  86438. (function (BABYLON) {
  86439. /**
  86440. * This represents a WebVR camera.
  86441. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86442. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86443. */
  86444. var WebVRFreeCamera = /** @class */ (function (_super) {
  86445. __extends(WebVRFreeCamera, _super);
  86446. /**
  86447. * Instantiates a WebVRFreeCamera.
  86448. * @param name The name of the WebVRFreeCamera
  86449. * @param position The starting anchor position for the camera
  86450. * @param scene The scene the camera belongs to
  86451. * @param webVROptions a set of customizable options for the webVRCamera
  86452. */
  86453. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86454. if (webVROptions === void 0) { webVROptions = {}; }
  86455. var _this = _super.call(this, name, position, scene) || this;
  86456. _this.webVROptions = webVROptions;
  86457. /**
  86458. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86459. */
  86460. _this._vrDevice = null;
  86461. /**
  86462. * The rawPose of the vrDevice.
  86463. */
  86464. _this.rawPose = null;
  86465. _this._specsVersion = "1.1";
  86466. _this._attached = false;
  86467. _this._descendants = [];
  86468. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86469. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86470. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86471. _this._standingMatrix = null;
  86472. /**
  86473. * Represents device position in babylon space.
  86474. */
  86475. _this.devicePosition = BABYLON.Vector3.Zero();
  86476. /**
  86477. * Represents device rotation in babylon space.
  86478. */
  86479. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86480. /**
  86481. * The scale of the device to be used when translating from device space to babylon space.
  86482. */
  86483. _this.deviceScaleFactor = 1;
  86484. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86485. _this._worldToDevice = BABYLON.Matrix.Identity();
  86486. /**
  86487. * References to the webVR controllers for the vrDevice.
  86488. */
  86489. _this.controllers = [];
  86490. /**
  86491. * Emits an event when a controller is attached.
  86492. */
  86493. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86494. /**
  86495. * Emits an event when a controller's mesh has been loaded;
  86496. */
  86497. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86498. /**
  86499. * If the rig cameras be used as parent instead of this camera.
  86500. */
  86501. _this.rigParenting = true;
  86502. _this._defaultHeight = undefined;
  86503. _this._workingVector = BABYLON.Vector3.Zero();
  86504. _this._oneVector = BABYLON.Vector3.One();
  86505. _this._workingMatrix = BABYLON.Matrix.Identity();
  86506. _this._cache.position = BABYLON.Vector3.Zero();
  86507. if (webVROptions.defaultHeight) {
  86508. _this._defaultHeight = webVROptions.defaultHeight;
  86509. _this.position.y = _this._defaultHeight;
  86510. }
  86511. _this.minZ = 0.1;
  86512. //legacy support - the compensation boolean was removed.
  86513. if (arguments.length === 5) {
  86514. _this.webVROptions = arguments[4];
  86515. }
  86516. // default webVR options
  86517. if (_this.webVROptions.trackPosition == undefined) {
  86518. _this.webVROptions.trackPosition = true;
  86519. }
  86520. if (_this.webVROptions.controllerMeshes == undefined) {
  86521. _this.webVROptions.controllerMeshes = true;
  86522. }
  86523. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86524. _this.webVROptions.defaultLightingOnControllers = true;
  86525. }
  86526. _this.rotationQuaternion = new BABYLON.Quaternion();
  86527. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86528. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86529. }
  86530. //enable VR
  86531. var engine = _this.getEngine();
  86532. _this._onVREnabled = function (success) { if (success) {
  86533. _this.initControllers();
  86534. } };
  86535. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86536. engine.initWebVR().add(function (event) {
  86537. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86538. return;
  86539. }
  86540. _this._vrDevice = event.vrDisplay;
  86541. //reset the rig parameters.
  86542. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86543. if (_this._attached) {
  86544. _this.getEngine().enableVR();
  86545. }
  86546. });
  86547. if (typeof (VRFrameData) !== "undefined")
  86548. _this._frameData = new VRFrameData();
  86549. /**
  86550. * The idea behind the following lines:
  86551. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86552. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86553. * the second will not show it correctly.
  86554. *
  86555. * To solve this - each object that has the camera as parent will be added to a protected array.
  86556. * When the rig camera renders, it will take this array and set all of those to be its children.
  86557. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86558. * Amazing!
  86559. */
  86560. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86561. if (camera.parent === _this && _this.rigParenting) {
  86562. _this._descendants = _this.getDescendants(true, function (n) {
  86563. // don't take the cameras or the controllers!
  86564. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86565. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86566. return !isController && !isRigCamera;
  86567. });
  86568. _this._descendants.forEach(function (node) {
  86569. node.parent = camera;
  86570. });
  86571. }
  86572. });
  86573. scene.onAfterCameraRenderObservable.add(function (camera) {
  86574. if (camera.parent === _this && _this.rigParenting) {
  86575. _this._descendants.forEach(function (node) {
  86576. node.parent = _this;
  86577. });
  86578. }
  86579. });
  86580. return _this;
  86581. }
  86582. /**
  86583. * Gets the device distance from the ground in meters.
  86584. * @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.
  86585. */
  86586. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86587. if (this._standingMatrix) {
  86588. // Add standing matrix offset to get real offset from ground in room
  86589. this._standingMatrix.getTranslationToRef(this._workingVector);
  86590. return this._deviceRoomPosition.y + this._workingVector.y;
  86591. }
  86592. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86593. return this._defaultHeight || 0;
  86594. };
  86595. /**
  86596. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86597. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86598. */
  86599. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86600. var _this = this;
  86601. if (callback === void 0) { callback = function (bool) { }; }
  86602. // Use standing matrix if available
  86603. this.getEngine().initWebVRAsync().then(function (result) {
  86604. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86605. callback(false);
  86606. }
  86607. else {
  86608. _this._standingMatrix = new BABYLON.Matrix();
  86609. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86610. if (!_this.getScene().useRightHandedSystem) {
  86611. [2, 6, 8, 9, 14].forEach(function (num) {
  86612. if (_this._standingMatrix) {
  86613. _this._standingMatrix.m[num] *= -1;
  86614. }
  86615. });
  86616. }
  86617. callback(true);
  86618. }
  86619. });
  86620. };
  86621. /**
  86622. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86623. * @returns A promise with a boolean set to if the standing matrix is supported.
  86624. */
  86625. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86626. var _this = this;
  86627. return new Promise(function (res, rej) {
  86628. _this.useStandingMatrix(function (supported) {
  86629. res(supported);
  86630. });
  86631. });
  86632. };
  86633. /**
  86634. * Disposes the camera
  86635. */
  86636. WebVRFreeCamera.prototype.dispose = function () {
  86637. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86638. _super.prototype.dispose.call(this);
  86639. };
  86640. /**
  86641. * Gets a vrController by name.
  86642. * @param name The name of the controller to retreive
  86643. * @returns the controller matching the name specified or null if not found
  86644. */
  86645. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86646. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86647. var gp = _a[_i];
  86648. if (gp.hand === name) {
  86649. return gp;
  86650. }
  86651. }
  86652. return null;
  86653. };
  86654. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86655. /**
  86656. * The controller corrisponding to the users left hand.
  86657. */
  86658. get: function () {
  86659. if (!this._leftController) {
  86660. this._leftController = this.getControllerByName("left");
  86661. }
  86662. return this._leftController;
  86663. },
  86664. enumerable: true,
  86665. configurable: true
  86666. });
  86667. ;
  86668. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86669. /**
  86670. * The controller corrisponding to the users right hand.
  86671. */
  86672. get: function () {
  86673. if (!this._rightController) {
  86674. this._rightController = this.getControllerByName("right");
  86675. }
  86676. return this._rightController;
  86677. },
  86678. enumerable: true,
  86679. configurable: true
  86680. });
  86681. ;
  86682. /**
  86683. * Casts a ray forward from the vrCamera's gaze.
  86684. * @param length Length of the ray (default: 100)
  86685. * @returns the ray corrisponding to the gaze
  86686. */
  86687. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86688. if (length === void 0) { length = 100; }
  86689. if (this.leftCamera) {
  86690. // Use left eye to avoid computation to compute center on every call
  86691. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86692. }
  86693. else {
  86694. return _super.prototype.getForwardRay.call(this, length);
  86695. }
  86696. };
  86697. /**
  86698. * Updates the camera based on device's frame data
  86699. */
  86700. WebVRFreeCamera.prototype._checkInputs = function () {
  86701. if (this._vrDevice && this._vrDevice.isPresenting) {
  86702. this._vrDevice.getFrameData(this._frameData);
  86703. this.updateFromDevice(this._frameData.pose);
  86704. }
  86705. _super.prototype._checkInputs.call(this);
  86706. };
  86707. /**
  86708. * Updates the poseControlled values based on the input device pose.
  86709. * @param poseData Pose coming from the device
  86710. */
  86711. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86712. if (poseData && poseData.orientation) {
  86713. this.rawPose = poseData;
  86714. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86715. if (this.getScene().useRightHandedSystem) {
  86716. this._deviceRoomRotationQuaternion.z *= -1;
  86717. this._deviceRoomRotationQuaternion.w *= -1;
  86718. }
  86719. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86720. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86721. if (this.getScene().useRightHandedSystem) {
  86722. this._deviceRoomPosition.z *= -1;
  86723. }
  86724. }
  86725. }
  86726. };
  86727. /**
  86728. * WebVR's attach control will start broadcasting frames to the device.
  86729. * Note that in certain browsers (chrome for example) this function must be called
  86730. * within a user-interaction callback. Example:
  86731. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86732. *
  86733. * @param element html element to attach the vrDevice to
  86734. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86735. */
  86736. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86737. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86738. this._attached = true;
  86739. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86740. if (this._vrDevice) {
  86741. this.getEngine().enableVR();
  86742. }
  86743. };
  86744. /**
  86745. * Detaches the camera from the html element and disables VR
  86746. *
  86747. * @param element html element to detach from
  86748. */
  86749. WebVRFreeCamera.prototype.detachControl = function (element) {
  86750. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86751. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86752. _super.prototype.detachControl.call(this, element);
  86753. this._attached = false;
  86754. this.getEngine().disableVR();
  86755. };
  86756. /**
  86757. * @returns the name of this class
  86758. */
  86759. WebVRFreeCamera.prototype.getClassName = function () {
  86760. return "WebVRFreeCamera";
  86761. };
  86762. /**
  86763. * Calls resetPose on the vrDisplay
  86764. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86765. */
  86766. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86767. //uses the vrDisplay's "resetPose()".
  86768. //pitch and roll won't be affected.
  86769. this._vrDevice.resetPose();
  86770. };
  86771. /**
  86772. * Updates the rig cameras (left and right eye)
  86773. */
  86774. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86775. var camLeft = this._rigCameras[0];
  86776. var camRight = this._rigCameras[1];
  86777. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86778. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86779. camLeft.position.copyFrom(this._deviceRoomPosition);
  86780. camRight.position.copyFrom(this._deviceRoomPosition);
  86781. };
  86782. /**
  86783. * Updates the cached values of the camera
  86784. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86785. */
  86786. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86787. var _this = this;
  86788. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86789. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86790. if (!this.updateCacheCalled) {
  86791. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86792. this.updateCacheCalled = true;
  86793. this.update();
  86794. }
  86795. // Set working vector to the device position in room space rotated by the new rotation
  86796. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86797. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86798. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86799. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86800. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86801. // Add translation from anchor position
  86802. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86803. this._workingVector.addInPlace(this.position);
  86804. this._workingVector.subtractInPlace(this._cache.position);
  86805. this._deviceToWorld.setTranslation(this._workingVector);
  86806. // Set an inverted matrix to be used when updating the camera
  86807. this._deviceToWorld.invertToRef(this._worldToDevice);
  86808. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86809. this.controllers.forEach(function (controller) {
  86810. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86811. controller.update();
  86812. });
  86813. }
  86814. if (!ignoreParentClass) {
  86815. _super.prototype._updateCache.call(this);
  86816. }
  86817. this.updateCacheCalled = false;
  86818. };
  86819. /**
  86820. * Updates the current device position and rotation in the babylon world
  86821. */
  86822. WebVRFreeCamera.prototype.update = function () {
  86823. // Get current device position in babylon world
  86824. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86825. // Get current device rotation in babylon world
  86826. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86827. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86828. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86829. _super.prototype.update.call(this);
  86830. };
  86831. /**
  86832. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86833. * @returns an identity matrix
  86834. */
  86835. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86836. return BABYLON.Matrix.Identity();
  86837. };
  86838. /**
  86839. * This function is called by the two RIG cameras.
  86840. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86841. */
  86842. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86843. var _this = this;
  86844. // Update the parent camera prior to using a child camera to avoid desynchronization
  86845. var parentCamera = this._cameraRigParams["parentCamera"];
  86846. parentCamera._updateCache();
  86847. //WebVR 1.1
  86848. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86849. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86850. if (!this.getScene().useRightHandedSystem) {
  86851. [2, 6, 8, 9, 14].forEach(function (num) {
  86852. _this._webvrViewMatrix.m[num] *= -1;
  86853. });
  86854. }
  86855. // update the camera rotation matrix
  86856. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86857. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86858. // Computing target and final matrix
  86859. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86860. // should the view matrix be updated with scale and position offset?
  86861. if (parentCamera.deviceScaleFactor !== 1) {
  86862. this._webvrViewMatrix.invert();
  86863. // scale the position, if set
  86864. if (parentCamera.deviceScaleFactor) {
  86865. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86866. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86867. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86868. }
  86869. this._webvrViewMatrix.invert();
  86870. }
  86871. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86872. return this._webvrViewMatrix;
  86873. };
  86874. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86875. var _this = this;
  86876. var parentCamera = this.parent;
  86877. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86878. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86879. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86880. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86881. //babylon compatible matrix
  86882. if (!this.getScene().useRightHandedSystem) {
  86883. [8, 9, 10, 11].forEach(function (num) {
  86884. _this._projectionMatrix.m[num] *= -1;
  86885. });
  86886. }
  86887. return this._projectionMatrix;
  86888. };
  86889. /**
  86890. * Initializes the controllers and their meshes
  86891. */
  86892. WebVRFreeCamera.prototype.initControllers = function () {
  86893. var _this = this;
  86894. this.controllers = [];
  86895. var manager = this.getScene().gamepadManager;
  86896. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86897. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86898. var webVrController = gamepad;
  86899. if (webVrController.defaultModel) {
  86900. webVrController.defaultModel.setEnabled(false);
  86901. }
  86902. if (webVrController.hand === "right") {
  86903. _this._rightController = null;
  86904. }
  86905. if (webVrController.hand === "left") {
  86906. _this._leftController = null;
  86907. }
  86908. var controllerIndex = _this.controllers.indexOf(webVrController);
  86909. if (controllerIndex !== -1) {
  86910. _this.controllers.splice(controllerIndex, 1);
  86911. }
  86912. }
  86913. });
  86914. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86915. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86916. var webVrController_1 = gamepad;
  86917. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86918. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86919. if (_this.webVROptions.controllerMeshes) {
  86920. if (webVrController_1.defaultModel) {
  86921. webVrController_1.defaultModel.setEnabled(true);
  86922. }
  86923. else {
  86924. // Load the meshes
  86925. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86926. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86927. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86928. if (_this.webVROptions.defaultLightingOnControllers) {
  86929. if (!_this._lightOnControllers) {
  86930. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86931. }
  86932. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86933. var children = mesh.getChildren();
  86934. if (children.length !== 0) {
  86935. children.forEach(function (mesh) {
  86936. light.includedOnlyMeshes.push(mesh);
  86937. activateLightOnSubMeshes_1(mesh, light);
  86938. });
  86939. }
  86940. };
  86941. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86942. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86943. }
  86944. });
  86945. }
  86946. }
  86947. webVrController_1.attachToPoseControlledCamera(_this);
  86948. // since this is async - sanity check. Is the controller already stored?
  86949. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86950. //add to the controllers array
  86951. _this.controllers.push(webVrController_1);
  86952. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86953. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86954. // So we're overriding setting left & right manually to be sure
  86955. var firstViveWandDetected = false;
  86956. for (var i = 0; i < _this.controllers.length; i++) {
  86957. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86958. if (!firstViveWandDetected) {
  86959. firstViveWandDetected = true;
  86960. _this.controllers[i].hand = "left";
  86961. }
  86962. else {
  86963. _this.controllers[i].hand = "right";
  86964. }
  86965. }
  86966. }
  86967. //did we find enough controllers? Great! let the developer know.
  86968. if (_this.controllers.length >= 2) {
  86969. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86970. }
  86971. }
  86972. }
  86973. });
  86974. };
  86975. return WebVRFreeCamera;
  86976. }(BABYLON.FreeCamera));
  86977. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86978. })(BABYLON || (BABYLON = {}));
  86979. //# sourceMappingURL=babylon.webVRCamera.js.map
  86980. var BABYLON;
  86981. (function (BABYLON) {
  86982. // We're mainly based on the logic defined into the FreeCamera code
  86983. /**
  86984. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86985. * being tilted forward or back and left or right.
  86986. */
  86987. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86988. __extends(DeviceOrientationCamera, _super);
  86989. /**
  86990. * Creates a new device orientation camera
  86991. * @param name The name of the camera
  86992. * @param position The start position camera
  86993. * @param scene The scene the camera belongs to
  86994. */
  86995. function DeviceOrientationCamera(name, position, scene) {
  86996. var _this = _super.call(this, name, position, scene) || this;
  86997. _this._quaternionCache = new BABYLON.Quaternion();
  86998. _this.inputs.addDeviceOrientation();
  86999. return _this;
  87000. }
  87001. /**
  87002. * Gets the current instance class name ("DeviceOrientationCamera").
  87003. * This helps avoiding instanceof at run time.
  87004. * @returns the class name
  87005. */
  87006. DeviceOrientationCamera.prototype.getClassName = function () {
  87007. return "DeviceOrientationCamera";
  87008. };
  87009. /**
  87010. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87011. */
  87012. DeviceOrientationCamera.prototype._checkInputs = function () {
  87013. _super.prototype._checkInputs.call(this);
  87014. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87015. if (this._initialQuaternion) {
  87016. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87017. }
  87018. };
  87019. /**
  87020. * Reset the camera to its default orientation on the specified axis only.
  87021. * @param axis The axis to reset
  87022. */
  87023. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87024. var _this = this;
  87025. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87026. //can only work if this camera has a rotation quaternion already.
  87027. if (!this.rotationQuaternion)
  87028. return;
  87029. if (!this._initialQuaternion) {
  87030. this._initialQuaternion = new BABYLON.Quaternion();
  87031. }
  87032. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87033. ['x', 'y', 'z'].forEach(function (axisName) {
  87034. if (!axis[axisName]) {
  87035. _this._initialQuaternion[axisName] = 0;
  87036. }
  87037. else {
  87038. _this._initialQuaternion[axisName] *= -1;
  87039. }
  87040. });
  87041. this._initialQuaternion.normalize();
  87042. //force rotation update
  87043. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87044. };
  87045. return DeviceOrientationCamera;
  87046. }(BABYLON.FreeCamera));
  87047. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87048. })(BABYLON || (BABYLON = {}));
  87049. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87050. var BABYLON;
  87051. (function (BABYLON) {
  87052. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87053. __extends(VRDeviceOrientationFreeCamera, _super);
  87054. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87055. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87056. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87057. var _this = _super.call(this, name, position, scene) || this;
  87058. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87059. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87060. return _this;
  87061. }
  87062. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87063. return "VRDeviceOrientationFreeCamera";
  87064. };
  87065. return VRDeviceOrientationFreeCamera;
  87066. }(BABYLON.DeviceOrientationCamera));
  87067. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87068. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87069. __extends(VRDeviceOrientationGamepadCamera, _super);
  87070. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87071. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87072. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87073. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87074. _this.inputs.addGamepad();
  87075. return _this;
  87076. }
  87077. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87078. return "VRDeviceOrientationGamepadCamera";
  87079. };
  87080. return VRDeviceOrientationGamepadCamera;
  87081. }(VRDeviceOrientationFreeCamera));
  87082. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87083. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87084. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87085. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87086. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87087. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87088. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87089. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87090. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87091. _this.inputs.addVRDeviceOrientation();
  87092. return _this;
  87093. }
  87094. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87095. return "VRDeviceOrientationArcRotateCamera";
  87096. };
  87097. return VRDeviceOrientationArcRotateCamera;
  87098. }(BABYLON.ArcRotateCamera));
  87099. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87100. })(BABYLON || (BABYLON = {}));
  87101. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87102. var BABYLON;
  87103. (function (BABYLON) {
  87104. /**
  87105. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87106. */
  87107. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87108. __extends(AnaglyphFreeCamera, _super);
  87109. /**
  87110. * Creates a new AnaglyphFreeCamera
  87111. * @param name defines camera name
  87112. * @param position defines initial position
  87113. * @param interaxialDistance defines distance between each color axis
  87114. * @param scene defines the hosting scene
  87115. */
  87116. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87117. var _this = _super.call(this, name, position, scene) || this;
  87118. _this.interaxialDistance = interaxialDistance;
  87119. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87120. return _this;
  87121. }
  87122. /**
  87123. * Gets camera class name
  87124. * @returns AnaglyphFreeCamera
  87125. */
  87126. AnaglyphFreeCamera.prototype.getClassName = function () {
  87127. return "AnaglyphFreeCamera";
  87128. };
  87129. return AnaglyphFreeCamera;
  87130. }(BABYLON.FreeCamera));
  87131. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87132. /**
  87133. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87134. */
  87135. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87136. __extends(AnaglyphArcRotateCamera, _super);
  87137. /**
  87138. * Creates a new AnaglyphArcRotateCamera
  87139. * @param name defines camera name
  87140. * @param alpha defines alpha angle (in radians)
  87141. * @param beta defines beta angle (in radians)
  87142. * @param radius defines radius
  87143. * @param target defines camera target
  87144. * @param interaxialDistance defines distance between each color axis
  87145. * @param scene defines the hosting scene
  87146. */
  87147. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87148. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87149. _this.interaxialDistance = interaxialDistance;
  87150. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87151. return _this;
  87152. }
  87153. /**
  87154. * Gets camera class name
  87155. * @returns AnaglyphArcRotateCamera
  87156. */
  87157. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87158. return "AnaglyphArcRotateCamera";
  87159. };
  87160. return AnaglyphArcRotateCamera;
  87161. }(BABYLON.ArcRotateCamera));
  87162. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87163. /**
  87164. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87165. */
  87166. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87167. __extends(AnaglyphGamepadCamera, _super);
  87168. /**
  87169. * Creates a new AnaglyphGamepadCamera
  87170. * @param name defines camera name
  87171. * @param position defines initial position
  87172. * @param interaxialDistance defines distance between each color axis
  87173. * @param scene defines the hosting scene
  87174. */
  87175. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87176. var _this = _super.call(this, name, position, scene) || this;
  87177. _this.interaxialDistance = interaxialDistance;
  87178. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87179. return _this;
  87180. }
  87181. /**
  87182. * Gets camera class name
  87183. * @returns AnaglyphGamepadCamera
  87184. */
  87185. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87186. return "AnaglyphGamepadCamera";
  87187. };
  87188. return AnaglyphGamepadCamera;
  87189. }(BABYLON.GamepadCamera));
  87190. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87191. /**
  87192. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87193. */
  87194. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87195. __extends(AnaglyphUniversalCamera, _super);
  87196. /**
  87197. * Creates a new AnaglyphUniversalCamera
  87198. * @param name defines camera name
  87199. * @param position defines initial position
  87200. * @param interaxialDistance defines distance between each color axis
  87201. * @param scene defines the hosting scene
  87202. */
  87203. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87204. var _this = _super.call(this, name, position, scene) || this;
  87205. _this.interaxialDistance = interaxialDistance;
  87206. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87207. return _this;
  87208. }
  87209. /**
  87210. * Gets camera class name
  87211. * @returns AnaglyphUniversalCamera
  87212. */
  87213. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87214. return "AnaglyphUniversalCamera";
  87215. };
  87216. return AnaglyphUniversalCamera;
  87217. }(BABYLON.UniversalCamera));
  87218. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87219. /**
  87220. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87221. */
  87222. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87223. __extends(StereoscopicFreeCamera, _super);
  87224. /**
  87225. * Creates a new StereoscopicFreeCamera
  87226. * @param name defines camera name
  87227. * @param position defines initial position
  87228. * @param interaxialDistance defines distance between each color axis
  87229. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87230. * @param scene defines the hosting scene
  87231. */
  87232. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87233. var _this = _super.call(this, name, position, scene) || this;
  87234. _this.interaxialDistance = interaxialDistance;
  87235. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87236. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87237. return _this;
  87238. }
  87239. /**
  87240. * Gets camera class name
  87241. * @returns StereoscopicFreeCamera
  87242. */
  87243. StereoscopicFreeCamera.prototype.getClassName = function () {
  87244. return "StereoscopicFreeCamera";
  87245. };
  87246. return StereoscopicFreeCamera;
  87247. }(BABYLON.FreeCamera));
  87248. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87249. /**
  87250. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87251. */
  87252. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87253. __extends(StereoscopicArcRotateCamera, _super);
  87254. /**
  87255. * Creates a new StereoscopicArcRotateCamera
  87256. * @param name defines camera name
  87257. * @param alpha defines alpha angle (in radians)
  87258. * @param beta defines beta angle (in radians)
  87259. * @param radius defines radius
  87260. * @param target defines camera target
  87261. * @param interaxialDistance defines distance between each color axis
  87262. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87263. * @param scene defines the hosting scene
  87264. */
  87265. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87266. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87267. _this.interaxialDistance = interaxialDistance;
  87268. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87269. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87270. return _this;
  87271. }
  87272. /**
  87273. * Gets camera class name
  87274. * @returns StereoscopicArcRotateCamera
  87275. */
  87276. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87277. return "StereoscopicArcRotateCamera";
  87278. };
  87279. return StereoscopicArcRotateCamera;
  87280. }(BABYLON.ArcRotateCamera));
  87281. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87282. /**
  87283. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87284. */
  87285. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87286. __extends(StereoscopicGamepadCamera, _super);
  87287. /**
  87288. * Creates a new StereoscopicGamepadCamera
  87289. * @param name defines camera name
  87290. * @param position defines initial position
  87291. * @param interaxialDistance defines distance between each color axis
  87292. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87293. * @param scene defines the hosting scene
  87294. */
  87295. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87296. var _this = _super.call(this, name, position, scene) || this;
  87297. _this.interaxialDistance = interaxialDistance;
  87298. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87299. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87300. return _this;
  87301. }
  87302. /**
  87303. * Gets camera class name
  87304. * @returns StereoscopicGamepadCamera
  87305. */
  87306. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87307. return "StereoscopicGamepadCamera";
  87308. };
  87309. return StereoscopicGamepadCamera;
  87310. }(BABYLON.GamepadCamera));
  87311. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87312. /**
  87313. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87314. */
  87315. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87316. __extends(StereoscopicUniversalCamera, _super);
  87317. /**
  87318. * Creates a new StereoscopicUniversalCamera
  87319. * @param name defines camera name
  87320. * @param position defines initial position
  87321. * @param interaxialDistance defines distance between each color axis
  87322. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87323. * @param scene defines the hosting scene
  87324. */
  87325. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87326. var _this = _super.call(this, name, position, scene) || this;
  87327. _this.interaxialDistance = interaxialDistance;
  87328. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87329. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87330. return _this;
  87331. }
  87332. /**
  87333. * Gets camera class name
  87334. * @returns StereoscopicUniversalCamera
  87335. */
  87336. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87337. return "StereoscopicUniversalCamera";
  87338. };
  87339. return StereoscopicUniversalCamera;
  87340. }(BABYLON.UniversalCamera));
  87341. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87342. })(BABYLON || (BABYLON = {}));
  87343. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87344. var BABYLON;
  87345. (function (BABYLON) {
  87346. var VRExperienceHelperGazer = /** @class */ (function () {
  87347. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87348. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87349. this.scene = scene;
  87350. this._pointerDownOnMeshAsked = false;
  87351. this._isActionableMesh = false;
  87352. this._teleportationRequestInitiated = false;
  87353. this._teleportationBackRequestInitiated = false;
  87354. this._dpadPressed = true;
  87355. this._activePointer = false;
  87356. this._id = VRExperienceHelperGazer._idCounter++;
  87357. // Gaze tracker
  87358. if (!gazeTrackerToClone) {
  87359. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87360. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87361. this._gazeTracker.isPickable = false;
  87362. this._gazeTracker.isVisible = false;
  87363. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87364. targetMat.specularColor = BABYLON.Color3.Black();
  87365. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87366. targetMat.backFaceCulling = false;
  87367. this._gazeTracker.material = targetMat;
  87368. }
  87369. else {
  87370. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87371. }
  87372. }
  87373. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87374. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87375. };
  87376. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87377. this._pointerDownOnMeshAsked = true;
  87378. if (this._currentMeshSelected && this._currentHit) {
  87379. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87380. }
  87381. };
  87382. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87383. if (this._currentMeshSelected && this._currentHit) {
  87384. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87385. }
  87386. this._pointerDownOnMeshAsked = false;
  87387. };
  87388. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87389. this._activePointer = true;
  87390. };
  87391. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87392. this._activePointer = false;
  87393. };
  87394. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87395. };
  87396. VRExperienceHelperGazer.prototype.dispose = function () {
  87397. this._interactionsEnabled = false;
  87398. this._teleportationEnabled = false;
  87399. };
  87400. VRExperienceHelperGazer._idCounter = 0;
  87401. return VRExperienceHelperGazer;
  87402. }());
  87403. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87404. __extends(VRExperienceHelperControllerGazer, _super);
  87405. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87406. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87407. _this.webVRController = webVRController;
  87408. // Laser pointer
  87409. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87410. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87411. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87412. laserPointerMaterial.alpha = 0.6;
  87413. _this._laserPointer.material = laserPointerMaterial;
  87414. _this._laserPointer.rotation.x = Math.PI / 2;
  87415. _this._laserPointer.position.z = -0.5;
  87416. _this._laserPointer.isVisible = false;
  87417. if (!webVRController.mesh) {
  87418. // Create an empty mesh that is used prior to loading the high quality model
  87419. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87420. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87421. preloadPointerPose.rotation.x = -0.7;
  87422. preloadMesh.addChild(preloadPointerPose);
  87423. webVRController.attachToMesh(preloadMesh);
  87424. }
  87425. _this._setLaserPointerParent(webVRController.mesh);
  87426. return _this;
  87427. }
  87428. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87429. return this.webVRController.getForwardRay(length);
  87430. };
  87431. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87432. _super.prototype._activatePointer.call(this);
  87433. this._laserPointer.isVisible = true;
  87434. };
  87435. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87436. _super.prototype._deactivatePointer.call(this);
  87437. this._laserPointer.isVisible = false;
  87438. };
  87439. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87440. this._laserPointer.material.emissiveColor = color;
  87441. };
  87442. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87443. var makeNotPick = function (root) {
  87444. root.name += " laserPointer";
  87445. root.getChildMeshes().forEach(function (c) {
  87446. makeNotPick(c);
  87447. });
  87448. };
  87449. makeNotPick(mesh);
  87450. var childMeshes = mesh.getChildMeshes();
  87451. this.webVRController._pointingPoseNode = null;
  87452. for (var i = 0; i < childMeshes.length; i++) {
  87453. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87454. mesh = childMeshes[i];
  87455. this.webVRController._pointingPoseNode = mesh;
  87456. break;
  87457. }
  87458. }
  87459. this._laserPointer.parent = mesh;
  87460. };
  87461. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87462. this._laserPointer.scaling.y = distance;
  87463. this._laserPointer.position.z = -distance / 2;
  87464. };
  87465. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87466. _super.prototype.dispose.call(this);
  87467. this._laserPointer.dispose();
  87468. };
  87469. return VRExperienceHelperControllerGazer;
  87470. }(VRExperienceHelperGazer));
  87471. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87472. __extends(VRExperienceHelperCameraGazer, _super);
  87473. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87474. var _this = _super.call(this, scene) || this;
  87475. _this.getCamera = getCamera;
  87476. return _this;
  87477. }
  87478. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87479. var camera = this.getCamera();
  87480. if (camera) {
  87481. return camera.getForwardRay(length);
  87482. }
  87483. else {
  87484. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87485. }
  87486. };
  87487. return VRExperienceHelperCameraGazer;
  87488. }(VRExperienceHelperGazer));
  87489. /**
  87490. * Helps to quickly add VR support to an existing scene.
  87491. * See http://doc.babylonjs.com/how_to/webvr_helper
  87492. */
  87493. var VRExperienceHelper = /** @class */ (function () {
  87494. /**
  87495. * Instantiates a VRExperienceHelper.
  87496. * Helps to quickly add VR support to an existing scene.
  87497. * @param scene The scene the VRExperienceHelper belongs to.
  87498. * @param webVROptions Options to modify the vr experience helper's behavior.
  87499. */
  87500. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87501. if (webVROptions === void 0) { webVROptions = {}; }
  87502. var _this = this;
  87503. this.webVROptions = webVROptions;
  87504. // Can the system support WebVR, even if a headset isn't plugged in?
  87505. this._webVRsupported = false;
  87506. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87507. this._webVRready = false;
  87508. // Are we waiting for the requestPresent callback to complete?
  87509. this._webVRrequesting = false;
  87510. // Are we presenting to the headset right now?
  87511. this._webVRpresenting = false;
  87512. // Are we presenting in the fullscreen fallback?
  87513. this._fullscreenVRpresenting = false;
  87514. /**
  87515. * Observable raised when entering VR.
  87516. */
  87517. this.onEnteringVRObservable = new BABYLON.Observable();
  87518. /**
  87519. * Observable raised when exiting VR.
  87520. */
  87521. this.onExitingVRObservable = new BABYLON.Observable();
  87522. /**
  87523. * Observable raised when controller mesh is loaded.
  87524. */
  87525. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87526. this._useCustomVRButton = false;
  87527. this._teleportationRequested = false;
  87528. this._teleportActive = false;
  87529. this._floorMeshesCollection = [];
  87530. this._rotationAllowed = true;
  87531. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87532. this._rotationRightAsked = false;
  87533. this._rotationLeftAsked = false;
  87534. this._isDefaultTeleportationTarget = true;
  87535. this._teleportationFillColor = "#444444";
  87536. this._teleportationBorderColor = "#FFFFFF";
  87537. this._rotationAngle = 0;
  87538. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87539. this._padSensibilityUp = 0.65;
  87540. this._padSensibilityDown = 0.35;
  87541. this.leftController = null;
  87542. this.rightController = null;
  87543. /**
  87544. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87545. */
  87546. this.onNewMeshSelected = new BABYLON.Observable();
  87547. /**
  87548. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87549. */
  87550. this.onNewMeshPicked = new BABYLON.Observable();
  87551. /**
  87552. * Observable raised before camera teleportation
  87553. */
  87554. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87555. /**
  87556. * Observable raised after camera teleportation
  87557. */
  87558. this.onAfterCameraTeleport = new BABYLON.Observable();
  87559. /**
  87560. * Observable raised when current selected mesh gets unselected
  87561. */
  87562. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87563. /**
  87564. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87565. */
  87566. this.teleportationEnabled = true;
  87567. this._teleportationInitialized = false;
  87568. this._interactionsEnabled = false;
  87569. this._interactionsRequested = false;
  87570. this._displayGaze = true;
  87571. this._displayLaserPointer = true;
  87572. this._onResize = function () {
  87573. _this.moveButtonToBottomRight();
  87574. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87575. _this.exitVR();
  87576. }
  87577. };
  87578. this._onFullscreenChange = function () {
  87579. if (document.fullscreen !== undefined) {
  87580. _this._fullscreenVRpresenting = document.fullscreen;
  87581. }
  87582. else if (document.mozFullScreen !== undefined) {
  87583. _this._fullscreenVRpresenting = document.mozFullScreen;
  87584. }
  87585. else if (document.webkitIsFullScreen !== undefined) {
  87586. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87587. }
  87588. else if (document.msIsFullScreen !== undefined) {
  87589. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87590. }
  87591. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87592. _this.exitVR();
  87593. if (!_this._useCustomVRButton) {
  87594. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87595. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87596. }
  87597. }
  87598. };
  87599. this.beforeRender = function () {
  87600. if (_this.leftController && _this.leftController._activePointer) {
  87601. _this._castRayAndSelectObject(_this.leftController);
  87602. }
  87603. if (_this.rightController && _this.rightController._activePointer) {
  87604. _this._castRayAndSelectObject(_this.rightController);
  87605. }
  87606. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87607. _this._castRayAndSelectObject(_this._cameraGazer);
  87608. }
  87609. else {
  87610. _this._cameraGazer._gazeTracker.isVisible = false;
  87611. }
  87612. };
  87613. this._onNewGamepadConnected = function (gamepad) {
  87614. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87615. if (gamepad.leftStick) {
  87616. gamepad.onleftstickchanged(function (stickValues) {
  87617. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87618. // Listening to classic/xbox gamepad only if no VR controller is active
  87619. if ((!_this.leftController && !_this.rightController) ||
  87620. ((_this.leftController && !_this.leftController._activePointer) &&
  87621. (_this.rightController && !_this.rightController._activePointer))) {
  87622. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87623. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87624. }
  87625. }
  87626. });
  87627. }
  87628. if (gamepad.rightStick) {
  87629. gamepad.onrightstickchanged(function (stickValues) {
  87630. if (_this._teleportationInitialized) {
  87631. _this._checkRotate(stickValues, _this._cameraGazer);
  87632. }
  87633. });
  87634. }
  87635. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87636. gamepad.onbuttondown(function (buttonPressed) {
  87637. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87638. _this._cameraGazer._selectionPointerDown();
  87639. }
  87640. });
  87641. gamepad.onbuttonup(function (buttonPressed) {
  87642. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87643. _this._cameraGazer._selectionPointerUp();
  87644. }
  87645. });
  87646. }
  87647. }
  87648. else {
  87649. var webVRController = gamepad;
  87650. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87651. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87652. _this.rightController = controller;
  87653. }
  87654. else {
  87655. _this.leftController = controller;
  87656. }
  87657. _this._tryEnableInteractionOnController(controller);
  87658. }
  87659. };
  87660. // 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
  87661. this._tryEnableInteractionOnController = function (controller) {
  87662. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87663. _this._enableInteractionOnController(controller);
  87664. }
  87665. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87666. _this._enableTeleportationOnController(controller);
  87667. }
  87668. };
  87669. this._onNewGamepadDisconnected = function (gamepad) {
  87670. if (gamepad instanceof BABYLON.WebVRController) {
  87671. if (gamepad.hand === "left" && _this.leftController != null) {
  87672. _this.leftController.dispose();
  87673. _this.leftController = null;
  87674. }
  87675. if (gamepad.hand === "right" && _this.rightController != null) {
  87676. _this.rightController.dispose();
  87677. _this.rightController = null;
  87678. }
  87679. }
  87680. };
  87681. this._workingVector = BABYLON.Vector3.Zero();
  87682. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87683. this._workingMatrix = BABYLON.Matrix.Identity();
  87684. this._scene = scene;
  87685. this._canvas = scene.getEngine().getRenderingCanvas();
  87686. // Parse options
  87687. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87688. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87689. }
  87690. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87691. webVROptions.createDeviceOrientationCamera = true;
  87692. }
  87693. if (webVROptions.defaultHeight === undefined) {
  87694. webVROptions.defaultHeight = 1.7;
  87695. }
  87696. if (webVROptions.useCustomVRButton) {
  87697. this._useCustomVRButton = true;
  87698. if (webVROptions.customVRButton) {
  87699. this._btnVR = webVROptions.customVRButton;
  87700. }
  87701. }
  87702. if (webVROptions.rayLength) {
  87703. this._rayLength = webVROptions.rayLength;
  87704. }
  87705. this._defaultHeight = webVROptions.defaultHeight;
  87706. if (webVROptions.positionScale) {
  87707. this._rayLength *= webVROptions.positionScale;
  87708. this._defaultHeight *= webVROptions.positionScale;
  87709. }
  87710. // Set position
  87711. if (this._scene.activeCamera) {
  87712. this._position = this._scene.activeCamera.position.clone();
  87713. }
  87714. else {
  87715. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87716. }
  87717. // Set non-vr camera
  87718. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87719. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87720. // Copy data from existing camera
  87721. if (this._scene.activeCamera) {
  87722. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87723. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87724. // Set rotation from previous camera
  87725. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87726. var targetCamera = this._scene.activeCamera;
  87727. if (targetCamera.rotationQuaternion) {
  87728. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87729. }
  87730. else {
  87731. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87732. }
  87733. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87734. }
  87735. }
  87736. this._scene.activeCamera = this._deviceOrientationCamera;
  87737. if (this._canvas) {
  87738. this._scene.activeCamera.attachControl(this._canvas);
  87739. }
  87740. }
  87741. else {
  87742. this._existingCamera = this._scene.activeCamera;
  87743. }
  87744. // Create VR cameras
  87745. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87746. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87747. }
  87748. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87749. this._webVRCamera.useStandingMatrix();
  87750. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87751. // Create default button
  87752. if (!this._useCustomVRButton) {
  87753. this._btnVR = document.createElement("BUTTON");
  87754. this._btnVR.className = "babylonVRicon";
  87755. this._btnVR.id = "babylonVRiconbtn";
  87756. this._btnVR.title = "Click to switch to VR";
  87757. 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) }";
  87758. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87759. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87760. // css += ".babylonVRicon.vrdisplaysupported { }";
  87761. // css += ".babylonVRicon.vrdisplayready { }";
  87762. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87763. var style = document.createElement('style');
  87764. style.appendChild(document.createTextNode(css));
  87765. document.getElementsByTagName('head')[0].appendChild(style);
  87766. this.moveButtonToBottomRight();
  87767. }
  87768. // VR button click event
  87769. if (this._btnVR) {
  87770. this._btnVR.addEventListener("click", function () {
  87771. if (!_this.isInVRMode) {
  87772. _this.enterVR();
  87773. }
  87774. else {
  87775. _this.exitVR();
  87776. }
  87777. });
  87778. }
  87779. // Window events
  87780. window.addEventListener("resize", this._onResize);
  87781. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87782. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87783. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87784. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87785. // Display vr button when headset is connected
  87786. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87787. this.displayVRButton();
  87788. }
  87789. else {
  87790. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87791. if (e.vrDisplay) {
  87792. _this.displayVRButton();
  87793. }
  87794. });
  87795. }
  87796. // Exiting VR mode using 'ESC' key on desktop
  87797. this._onKeyDown = function (event) {
  87798. if (event.keyCode === 27 && _this.isInVRMode) {
  87799. _this.exitVR();
  87800. }
  87801. };
  87802. document.addEventListener("keydown", this._onKeyDown);
  87803. // Exiting VR mode double tapping the touch screen
  87804. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87805. if (_this.isInVRMode) {
  87806. _this.exitVR();
  87807. if (_this._fullscreenVRpresenting) {
  87808. _this._scene.getEngine().switchFullscreen(true);
  87809. }
  87810. }
  87811. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87812. // Listen for WebVR display changes
  87813. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87814. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87815. this._onVRRequestPresentStart = function () {
  87816. _this._webVRrequesting = true;
  87817. _this.updateButtonVisibility();
  87818. };
  87819. this._onVRRequestPresentComplete = function (success) {
  87820. _this._webVRrequesting = false;
  87821. _this.updateButtonVisibility();
  87822. };
  87823. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87824. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87825. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87826. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87827. scene.onDisposeObservable.add(function () {
  87828. _this.dispose();
  87829. });
  87830. // Gamepad connection events
  87831. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87832. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87833. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87834. this.updateButtonVisibility();
  87835. //create easing functions
  87836. this._circleEase = new BABYLON.CircleEase();
  87837. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87838. }
  87839. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87840. /** Return this.onEnteringVRObservable
  87841. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87842. */
  87843. get: function () {
  87844. return this.onEnteringVRObservable;
  87845. },
  87846. enumerable: true,
  87847. configurable: true
  87848. });
  87849. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87850. /** Return this.onExitingVRObservable
  87851. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87852. */
  87853. get: function () {
  87854. return this.onExitingVRObservable;
  87855. },
  87856. enumerable: true,
  87857. configurable: true
  87858. });
  87859. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87860. /** Return this.onControllerMeshLoadedObservable
  87861. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87862. */
  87863. get: function () {
  87864. return this.onControllerMeshLoadedObservable;
  87865. },
  87866. enumerable: true,
  87867. configurable: true
  87868. });
  87869. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87870. /**
  87871. * The mesh used to display where the user is going to teleport.
  87872. */
  87873. get: function () {
  87874. return this._teleportationTarget;
  87875. },
  87876. /**
  87877. * Sets the mesh to be used to display where the user is going to teleport.
  87878. */
  87879. set: function (value) {
  87880. if (value) {
  87881. value.name = "teleportationTarget";
  87882. this._isDefaultTeleportationTarget = false;
  87883. this._teleportationTarget = value;
  87884. }
  87885. },
  87886. enumerable: true,
  87887. configurable: true
  87888. });
  87889. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87890. /**
  87891. * The mesh used to display where the user is selecting,
  87892. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87893. * See http://doc.babylonjs.com/resources/baking_transformations
  87894. */
  87895. get: function () {
  87896. return this._cameraGazer._gazeTracker;
  87897. },
  87898. set: function (value) {
  87899. if (value) {
  87900. this._cameraGazer._gazeTracker = value;
  87901. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87902. this._cameraGazer._gazeTracker.isPickable = false;
  87903. this._cameraGazer._gazeTracker.isVisible = false;
  87904. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87905. if (this.leftController) {
  87906. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87907. }
  87908. if (this.rightController) {
  87909. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87910. }
  87911. }
  87912. },
  87913. enumerable: true,
  87914. configurable: true
  87915. });
  87916. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87917. /**
  87918. * If the ray of the gaze should be displayed.
  87919. */
  87920. get: function () {
  87921. return this._displayGaze;
  87922. },
  87923. /**
  87924. * Sets if the ray of the gaze should be displayed.
  87925. */
  87926. set: function (value) {
  87927. this._displayGaze = value;
  87928. if (!value) {
  87929. this._cameraGazer._gazeTracker.isVisible = false;
  87930. if (this.leftController) {
  87931. this.leftController._gazeTracker.isVisible = false;
  87932. }
  87933. if (this.rightController) {
  87934. this.rightController._gazeTracker.isVisible = false;
  87935. }
  87936. }
  87937. },
  87938. enumerable: true,
  87939. configurable: true
  87940. });
  87941. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87942. /**
  87943. * If the ray of the LaserPointer should be displayed.
  87944. */
  87945. get: function () {
  87946. return this._displayLaserPointer;
  87947. },
  87948. /**
  87949. * Sets if the ray of the LaserPointer should be displayed.
  87950. */
  87951. set: function (value) {
  87952. this._displayLaserPointer = value;
  87953. if (!value) {
  87954. if (this.rightController) {
  87955. this.rightController._deactivatePointer();
  87956. this.rightController._gazeTracker.isVisible = false;
  87957. }
  87958. if (this.leftController) {
  87959. this.leftController._deactivatePointer();
  87960. this.leftController._gazeTracker.isVisible = false;
  87961. }
  87962. }
  87963. else {
  87964. if (this.rightController) {
  87965. this.rightController._activatePointer();
  87966. }
  87967. else if (this.leftController) {
  87968. this.leftController._activatePointer();
  87969. }
  87970. }
  87971. },
  87972. enumerable: true,
  87973. configurable: true
  87974. });
  87975. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87976. /**
  87977. * The deviceOrientationCamera used as the camera when not in VR.
  87978. */
  87979. get: function () {
  87980. return this._deviceOrientationCamera;
  87981. },
  87982. enumerable: true,
  87983. configurable: true
  87984. });
  87985. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87986. /**
  87987. * Based on the current WebVR support, returns the current VR camera used.
  87988. */
  87989. get: function () {
  87990. if (this._webVRready) {
  87991. return this._webVRCamera;
  87992. }
  87993. else {
  87994. return this._scene.activeCamera;
  87995. }
  87996. },
  87997. enumerable: true,
  87998. configurable: true
  87999. });
  88000. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88001. /**
  88002. * The webVRCamera which is used when in VR.
  88003. */
  88004. get: function () {
  88005. return this._webVRCamera;
  88006. },
  88007. enumerable: true,
  88008. configurable: true
  88009. });
  88010. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88011. /**
  88012. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88013. */
  88014. get: function () {
  88015. return this._vrDeviceOrientationCamera;
  88016. },
  88017. enumerable: true,
  88018. configurable: true
  88019. });
  88020. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88021. get: function () {
  88022. var result = this._cameraGazer._teleportationRequestInitiated
  88023. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88024. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88025. return result;
  88026. },
  88027. enumerable: true,
  88028. configurable: true
  88029. });
  88030. // Raised when one of the controller has loaded successfully its associated default mesh
  88031. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88032. if (this.leftController && this.leftController.webVRController == webVRController) {
  88033. if (webVRController.mesh) {
  88034. this.leftController._setLaserPointerParent(webVRController.mesh);
  88035. }
  88036. }
  88037. if (this.rightController && this.rightController.webVRController == webVRController) {
  88038. if (webVRController.mesh) {
  88039. this.rightController._setLaserPointerParent(webVRController.mesh);
  88040. }
  88041. }
  88042. try {
  88043. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88044. }
  88045. catch (err) {
  88046. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88047. }
  88048. };
  88049. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88050. /**
  88051. * Gets a value indicating if we are currently in VR mode.
  88052. */
  88053. get: function () {
  88054. return this._webVRpresenting || this._fullscreenVRpresenting;
  88055. },
  88056. enumerable: true,
  88057. configurable: true
  88058. });
  88059. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88060. var vrDisplay = this._scene.getEngine().getVRDevice();
  88061. if (vrDisplay) {
  88062. var wasPresenting = this._webVRpresenting;
  88063. // A VR display is connected
  88064. this._webVRpresenting = vrDisplay.isPresenting;
  88065. if (wasPresenting && !this._webVRpresenting)
  88066. this.exitVR();
  88067. }
  88068. else {
  88069. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88070. }
  88071. this.updateButtonVisibility();
  88072. };
  88073. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88074. this._webVRsupported = eventArgs.vrSupported;
  88075. this._webVRready = !!eventArgs.vrDisplay;
  88076. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88077. this.updateButtonVisibility();
  88078. };
  88079. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88080. if (this._canvas && !this._useCustomVRButton) {
  88081. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88082. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88083. }
  88084. };
  88085. VRExperienceHelper.prototype.displayVRButton = function () {
  88086. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88087. document.body.appendChild(this._btnVR);
  88088. this._btnVRDisplayed = true;
  88089. }
  88090. };
  88091. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88092. if (!this._btnVR || this._useCustomVRButton) {
  88093. return;
  88094. }
  88095. this._btnVR.className = "babylonVRicon";
  88096. if (this.isInVRMode) {
  88097. this._btnVR.className += " vrdisplaypresenting";
  88098. }
  88099. else {
  88100. if (this._webVRready)
  88101. this._btnVR.className += " vrdisplayready";
  88102. if (this._webVRsupported)
  88103. this._btnVR.className += " vrdisplaysupported";
  88104. if (this._webVRrequesting)
  88105. this._btnVR.className += " vrdisplayrequesting";
  88106. }
  88107. };
  88108. /**
  88109. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88110. * Otherwise, will use the fullscreen API.
  88111. */
  88112. VRExperienceHelper.prototype.enterVR = function () {
  88113. if (this.onEnteringVRObservable) {
  88114. try {
  88115. this.onEnteringVRObservable.notifyObservers(this);
  88116. }
  88117. catch (err) {
  88118. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88119. }
  88120. }
  88121. if (this._scene.activeCamera) {
  88122. this._position = this._scene.activeCamera.position.clone();
  88123. // make sure that we return to the last active camera
  88124. this._existingCamera = this._scene.activeCamera;
  88125. }
  88126. if (this._webVRrequesting)
  88127. return;
  88128. // If WebVR is supported and a headset is connected
  88129. if (this._webVRready) {
  88130. if (!this._webVRpresenting) {
  88131. this._webVRCamera.position = this._position;
  88132. this._scene.activeCamera = this._webVRCamera;
  88133. }
  88134. }
  88135. else if (this._vrDeviceOrientationCamera) {
  88136. this._vrDeviceOrientationCamera.position = this._position;
  88137. if (this._scene.activeCamera) {
  88138. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88139. }
  88140. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88141. this._scene.getEngine().switchFullscreen(true);
  88142. this.updateButtonVisibility();
  88143. }
  88144. if (this._scene.activeCamera && this._canvas) {
  88145. this._scene.activeCamera.attachControl(this._canvas);
  88146. }
  88147. if (this._interactionsEnabled) {
  88148. this._scene.registerBeforeRender(this.beforeRender);
  88149. }
  88150. };
  88151. /**
  88152. * Attempt to exit VR, or fullscreen.
  88153. */
  88154. VRExperienceHelper.prototype.exitVR = function () {
  88155. if (this.onExitingVRObservable) {
  88156. try {
  88157. this.onExitingVRObservable.notifyObservers(this);
  88158. }
  88159. catch (err) {
  88160. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88161. }
  88162. }
  88163. if (this._webVRpresenting) {
  88164. this._scene.getEngine().disableVR();
  88165. }
  88166. if (this._scene.activeCamera) {
  88167. this._position = this._scene.activeCamera.position.clone();
  88168. }
  88169. if (this._deviceOrientationCamera) {
  88170. this._deviceOrientationCamera.position = this._position;
  88171. this._scene.activeCamera = this._deviceOrientationCamera;
  88172. if (this._canvas) {
  88173. this._scene.activeCamera.attachControl(this._canvas);
  88174. }
  88175. }
  88176. else if (this._existingCamera) {
  88177. this._existingCamera.position = this._position;
  88178. this._scene.activeCamera = this._existingCamera;
  88179. }
  88180. this.updateButtonVisibility();
  88181. if (this._interactionsEnabled) {
  88182. this._scene.unregisterBeforeRender(this.beforeRender);
  88183. }
  88184. // resize to update width and height when exiting vr exits fullscreen
  88185. this._scene.getEngine().resize();
  88186. };
  88187. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88188. /**
  88189. * The position of the vr experience helper.
  88190. */
  88191. get: function () {
  88192. return this._position;
  88193. },
  88194. /**
  88195. * Sets the position of the vr experience helper.
  88196. */
  88197. set: function (value) {
  88198. this._position = value;
  88199. if (this._scene.activeCamera) {
  88200. this._scene.activeCamera.position = value;
  88201. }
  88202. },
  88203. enumerable: true,
  88204. configurable: true
  88205. });
  88206. /**
  88207. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88208. */
  88209. VRExperienceHelper.prototype.enableInteractions = function () {
  88210. var _this = this;
  88211. if (!this._interactionsEnabled) {
  88212. this._interactionsRequested = true;
  88213. if (this.leftController) {
  88214. this._enableInteractionOnController(this.leftController);
  88215. }
  88216. if (this.rightController) {
  88217. this._enableInteractionOnController(this.rightController);
  88218. }
  88219. this.raySelectionPredicate = function (mesh) {
  88220. return mesh.isVisible;
  88221. };
  88222. this.meshSelectionPredicate = function (mesh) {
  88223. return true;
  88224. };
  88225. this._raySelectionPredicate = function (mesh) {
  88226. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88227. && mesh.name.indexOf("teleportationTarget") === -1
  88228. && mesh.name.indexOf("torusTeleportation") === -1
  88229. && mesh.name.indexOf("laserPointer") === -1)) {
  88230. return _this.raySelectionPredicate(mesh);
  88231. }
  88232. return false;
  88233. };
  88234. this._interactionsEnabled = true;
  88235. }
  88236. };
  88237. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88238. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88239. if (this._floorMeshesCollection[i].id === mesh.id) {
  88240. return true;
  88241. }
  88242. }
  88243. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88244. return true;
  88245. }
  88246. return false;
  88247. };
  88248. /**
  88249. * Adds a floor mesh to be used for teleportation.
  88250. * @param floorMesh the mesh to be used for teleportation.
  88251. */
  88252. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88253. if (!this._floorMeshesCollection) {
  88254. return;
  88255. }
  88256. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88257. return;
  88258. }
  88259. this._floorMeshesCollection.push(floorMesh);
  88260. };
  88261. /**
  88262. * Removes a floor mesh from being used for teleportation.
  88263. * @param floorMesh the mesh to be removed.
  88264. */
  88265. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88266. if (!this._floorMeshesCollection) {
  88267. return;
  88268. }
  88269. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88270. if (meshIndex !== -1) {
  88271. this._floorMeshesCollection.splice(meshIndex, 1);
  88272. }
  88273. };
  88274. /**
  88275. * Enables interactions and teleportation using the VR controllers and gaze.
  88276. * @param vrTeleportationOptions options to modify teleportation behavior.
  88277. */
  88278. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88279. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88280. if (!this._teleportationInitialized) {
  88281. this._teleportationRequested = true;
  88282. this.enableInteractions();
  88283. if (vrTeleportationOptions.floorMeshName) {
  88284. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88285. }
  88286. if (vrTeleportationOptions.floorMeshes) {
  88287. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88288. }
  88289. if (this.leftController != null) {
  88290. this._enableTeleportationOnController(this.leftController);
  88291. }
  88292. if (this.rightController != null) {
  88293. this._enableTeleportationOnController(this.rightController);
  88294. }
  88295. // Creates an image processing post process for the vignette not relying
  88296. // on the main scene configuration for image processing to reduce setup and spaces
  88297. // (gamma/linear) conflicts.
  88298. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88299. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88300. imageProcessingConfiguration.vignetteEnabled = true;
  88301. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88302. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88303. this._teleportationInitialized = true;
  88304. if (this._isDefaultTeleportationTarget) {
  88305. this._createTeleportationCircles();
  88306. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88307. }
  88308. }
  88309. };
  88310. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88311. var _this = this;
  88312. var controllerMesh = controller.webVRController.mesh;
  88313. if (controllerMesh) {
  88314. controller._interactionsEnabled = true;
  88315. controller._activatePointer();
  88316. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88317. // Enabling / disabling laserPointer
  88318. if (_this._displayLaserPointer && stateObject.value === 1) {
  88319. if (controller._activePointer) {
  88320. controller._deactivatePointer();
  88321. }
  88322. else {
  88323. controller._activatePointer();
  88324. }
  88325. if (_this.displayGaze) {
  88326. controller._gazeTracker.isVisible = controller._activePointer;
  88327. }
  88328. }
  88329. });
  88330. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88331. if (!controller._pointerDownOnMeshAsked) {
  88332. if (stateObject.value > _this._padSensibilityUp) {
  88333. controller._selectionPointerDown();
  88334. }
  88335. }
  88336. else if (stateObject.value < _this._padSensibilityDown) {
  88337. controller._selectionPointerUp();
  88338. }
  88339. });
  88340. }
  88341. };
  88342. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88343. // Dont teleport if another gaze already requested teleportation
  88344. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88345. return;
  88346. }
  88347. if (!gazer._teleportationRequestInitiated) {
  88348. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88349. gazer._activatePointer();
  88350. gazer._teleportationRequestInitiated = true;
  88351. }
  88352. }
  88353. else {
  88354. // Listening to the proper controller values changes to confirm teleportation
  88355. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88356. if (this._teleportActive) {
  88357. this._teleportCamera(this._haloCenter);
  88358. }
  88359. gazer._teleportationRequestInitiated = false;
  88360. }
  88361. }
  88362. };
  88363. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88364. // Only rotate when user is not currently selecting a teleportation location
  88365. if (gazer._teleportationRequestInitiated) {
  88366. return;
  88367. }
  88368. if (!this._rotationLeftAsked) {
  88369. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88370. this._rotationLeftAsked = true;
  88371. if (this._rotationAllowed) {
  88372. this._rotateCamera(false);
  88373. }
  88374. }
  88375. }
  88376. else {
  88377. if (stateObject.x > -this._padSensibilityDown) {
  88378. this._rotationLeftAsked = false;
  88379. }
  88380. }
  88381. if (!this._rotationRightAsked) {
  88382. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88383. this._rotationRightAsked = true;
  88384. if (this._rotationAllowed) {
  88385. this._rotateCamera(true);
  88386. }
  88387. }
  88388. }
  88389. else {
  88390. if (stateObject.x < this._padSensibilityDown) {
  88391. this._rotationRightAsked = false;
  88392. }
  88393. }
  88394. };
  88395. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88396. // Only teleport backwards when user is not currently selecting a teleportation location
  88397. if (gazer._teleportationRequestInitiated) {
  88398. return;
  88399. }
  88400. // Teleport backwards
  88401. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88402. if (!gazer._teleportationBackRequestInitiated) {
  88403. if (!this.currentVRCamera) {
  88404. return;
  88405. }
  88406. // Get rotation and position of the current camera
  88407. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88408. var position = this.currentVRCamera.position;
  88409. // If the camera has device position, use that instead
  88410. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88411. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88412. position = this.currentVRCamera.devicePosition;
  88413. }
  88414. // Get matrix with only the y rotation of the device rotation
  88415. rotation.toEulerAnglesToRef(this._workingVector);
  88416. this._workingVector.z = 0;
  88417. this._workingVector.x = 0;
  88418. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88419. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88420. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88421. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88422. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88423. var ray = new BABYLON.Ray(position, this._workingVector);
  88424. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88425. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88426. this._teleportCamera(hit.pickedPoint);
  88427. }
  88428. gazer._teleportationBackRequestInitiated = true;
  88429. }
  88430. }
  88431. else {
  88432. gazer._teleportationBackRequestInitiated = false;
  88433. }
  88434. };
  88435. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88436. var _this = this;
  88437. var controllerMesh = controller.webVRController.mesh;
  88438. if (controllerMesh) {
  88439. if (!controller._interactionsEnabled) {
  88440. this._enableInteractionOnController(controller);
  88441. }
  88442. controller._interactionsEnabled = true;
  88443. controller._teleportationEnabled = true;
  88444. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88445. controller._dpadPressed = false;
  88446. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88447. controller._dpadPressed = stateObject.pressed;
  88448. if (!controller._dpadPressed) {
  88449. _this._rotationLeftAsked = false;
  88450. _this._rotationRightAsked = false;
  88451. controller._teleportationBackRequestInitiated = false;
  88452. }
  88453. });
  88454. }
  88455. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88456. if (_this.teleportationEnabled) {
  88457. _this._checkTeleportBackwards(stateObject, controller);
  88458. _this._checkTeleportWithRay(stateObject, controller);
  88459. }
  88460. _this._checkRotate(stateObject, controller);
  88461. });
  88462. }
  88463. };
  88464. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88465. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88466. this._teleportationTarget.isPickable = false;
  88467. var length = 512;
  88468. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88469. dynamicTexture.hasAlpha = true;
  88470. var context = dynamicTexture.getContext();
  88471. var centerX = length / 2;
  88472. var centerY = length / 2;
  88473. var radius = 200;
  88474. context.beginPath();
  88475. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88476. context.fillStyle = this._teleportationFillColor;
  88477. context.fill();
  88478. context.lineWidth = 10;
  88479. context.strokeStyle = this._teleportationBorderColor;
  88480. context.stroke();
  88481. context.closePath();
  88482. dynamicTexture.update();
  88483. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88484. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88485. this._teleportationTarget.material = teleportationCircleMaterial;
  88486. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88487. torus.isPickable = false;
  88488. torus.parent = this._teleportationTarget;
  88489. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88490. var keys = [];
  88491. keys.push({
  88492. frame: 0,
  88493. value: 0
  88494. });
  88495. keys.push({
  88496. frame: 30,
  88497. value: 0.4
  88498. });
  88499. keys.push({
  88500. frame: 60,
  88501. value: 0
  88502. });
  88503. animationInnerCircle.setKeys(keys);
  88504. var easingFunction = new BABYLON.SineEase();
  88505. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88506. animationInnerCircle.setEasingFunction(easingFunction);
  88507. torus.animations = [];
  88508. torus.animations.push(animationInnerCircle);
  88509. this._scene.beginAnimation(torus, 0, 60, true);
  88510. this._hideTeleportationTarget();
  88511. };
  88512. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88513. this._teleportActive = true;
  88514. if (this._teleportationInitialized) {
  88515. this._teleportationTarget.isVisible = true;
  88516. if (this._isDefaultTeleportationTarget) {
  88517. this._teleportationTarget.getChildren()[0].isVisible = true;
  88518. }
  88519. }
  88520. };
  88521. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88522. this._teleportActive = false;
  88523. if (this._teleportationInitialized) {
  88524. this._teleportationTarget.isVisible = false;
  88525. if (this._isDefaultTeleportationTarget) {
  88526. this._teleportationTarget.getChildren()[0].isVisible = false;
  88527. }
  88528. }
  88529. };
  88530. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88531. var _this = this;
  88532. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88533. return;
  88534. }
  88535. if (right) {
  88536. this._rotationAngle++;
  88537. }
  88538. else {
  88539. this._rotationAngle--;
  88540. }
  88541. this.currentVRCamera.animations = [];
  88542. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88543. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88544. var animationRotationKeys = [];
  88545. animationRotationKeys.push({
  88546. frame: 0,
  88547. value: this.currentVRCamera.rotationQuaternion
  88548. });
  88549. animationRotationKeys.push({
  88550. frame: 6,
  88551. value: target
  88552. });
  88553. animationRotation.setKeys(animationRotationKeys);
  88554. animationRotation.setEasingFunction(this._circleEase);
  88555. this.currentVRCamera.animations.push(animationRotation);
  88556. this._postProcessMove.animations = [];
  88557. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88558. var vignetteWeightKeys = [];
  88559. vignetteWeightKeys.push({
  88560. frame: 0,
  88561. value: 0
  88562. });
  88563. vignetteWeightKeys.push({
  88564. frame: 3,
  88565. value: 4
  88566. });
  88567. vignetteWeightKeys.push({
  88568. frame: 6,
  88569. value: 0
  88570. });
  88571. animationPP.setKeys(vignetteWeightKeys);
  88572. animationPP.setEasingFunction(this._circleEase);
  88573. this._postProcessMove.animations.push(animationPP);
  88574. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88575. var vignetteStretchKeys = [];
  88576. vignetteStretchKeys.push({
  88577. frame: 0,
  88578. value: 0
  88579. });
  88580. vignetteStretchKeys.push({
  88581. frame: 3,
  88582. value: 10
  88583. });
  88584. vignetteStretchKeys.push({
  88585. frame: 6,
  88586. value: 0
  88587. });
  88588. animationPP2.setKeys(vignetteStretchKeys);
  88589. animationPP2.setEasingFunction(this._circleEase);
  88590. this._postProcessMove.animations.push(animationPP2);
  88591. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88592. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88593. this._postProcessMove.samples = 4;
  88594. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88595. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88596. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88597. });
  88598. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88599. };
  88600. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  88601. if (hit.pickedPoint) {
  88602. if (gazer._teleportationRequestInitiated) {
  88603. this._displayTeleportationTarget();
  88604. this._haloCenter.copyFrom(hit.pickedPoint);
  88605. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88606. }
  88607. var pickNormal = hit.getNormal(true, false);
  88608. if (pickNormal) {
  88609. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88610. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88611. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88612. }
  88613. this._teleportationTarget.position.y += 0.1;
  88614. }
  88615. };
  88616. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88617. var _this = this;
  88618. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88619. return;
  88620. }
  88621. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88622. // offset of the headset from the anchor.
  88623. if (this.webVRCamera.leftCamera) {
  88624. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88625. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88626. location.subtractToRef(this._workingVector, this._workingVector);
  88627. }
  88628. else {
  88629. this._workingVector.copyFrom(location);
  88630. }
  88631. // Add height to account for user's height offset
  88632. if (this.isInVRMode) {
  88633. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88634. }
  88635. else {
  88636. this._workingVector.y += this._defaultHeight;
  88637. }
  88638. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88639. // Create animation from the camera's position to the new location
  88640. this.currentVRCamera.animations = [];
  88641. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88642. var animationCameraTeleportationKeys = [{
  88643. frame: 0,
  88644. value: this.currentVRCamera.position
  88645. },
  88646. {
  88647. frame: 11,
  88648. value: this._workingVector
  88649. }
  88650. ];
  88651. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88652. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88653. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88654. this._postProcessMove.animations = [];
  88655. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88656. var vignetteWeightKeys = [];
  88657. vignetteWeightKeys.push({
  88658. frame: 0,
  88659. value: 0
  88660. });
  88661. vignetteWeightKeys.push({
  88662. frame: 5,
  88663. value: 8
  88664. });
  88665. vignetteWeightKeys.push({
  88666. frame: 11,
  88667. value: 0
  88668. });
  88669. animationPP.setKeys(vignetteWeightKeys);
  88670. this._postProcessMove.animations.push(animationPP);
  88671. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88672. var vignetteStretchKeys = [];
  88673. vignetteStretchKeys.push({
  88674. frame: 0,
  88675. value: 0
  88676. });
  88677. vignetteStretchKeys.push({
  88678. frame: 5,
  88679. value: 10
  88680. });
  88681. vignetteStretchKeys.push({
  88682. frame: 11,
  88683. value: 0
  88684. });
  88685. animationPP2.setKeys(vignetteStretchKeys);
  88686. this._postProcessMove.animations.push(animationPP2);
  88687. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88688. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88689. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88690. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88691. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88692. });
  88693. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88694. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88695. });
  88696. this._hideTeleportationTarget();
  88697. };
  88698. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88699. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88700. return;
  88701. }
  88702. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  88703. // Moving the gazeTracker on the mesh face targetted
  88704. if (hit && hit.pickedPoint) {
  88705. if (this._displayGaze) {
  88706. var multiplier = 1;
  88707. gazer._gazeTracker.isVisible = true;
  88708. if (gazer._isActionableMesh) {
  88709. multiplier = 3;
  88710. }
  88711. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88712. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88713. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88714. var pickNormal = hit.getNormal();
  88715. // To avoid z-fighting
  88716. var deltaFighting = 0.002;
  88717. if (pickNormal) {
  88718. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88719. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88720. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88721. }
  88722. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88723. if (gazer._gazeTracker.position.x < 0) {
  88724. gazer._gazeTracker.position.x += deltaFighting;
  88725. }
  88726. else {
  88727. gazer._gazeTracker.position.x -= deltaFighting;
  88728. }
  88729. if (gazer._gazeTracker.position.y < 0) {
  88730. gazer._gazeTracker.position.y += deltaFighting;
  88731. }
  88732. else {
  88733. gazer._gazeTracker.position.y -= deltaFighting;
  88734. }
  88735. if (gazer._gazeTracker.position.z < 0) {
  88736. gazer._gazeTracker.position.z += deltaFighting;
  88737. }
  88738. else {
  88739. gazer._gazeTracker.position.z -= deltaFighting;
  88740. }
  88741. }
  88742. // Changing the size of the laser pointer based on the distance from the targetted point
  88743. gazer._updatePointerDistance(hit.distance);
  88744. }
  88745. else {
  88746. gazer._gazeTracker.isVisible = false;
  88747. }
  88748. if (hit && hit.pickedMesh) {
  88749. gazer._currentHit = hit;
  88750. if (gazer._pointerDownOnMeshAsked) {
  88751. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88752. }
  88753. // The object selected is the floor, we're in a teleportation scenario
  88754. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88755. // Moving the teleportation area to this targetted point
  88756. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88757. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88758. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88759. }
  88760. gazer._currentMeshSelected = null;
  88761. if (gazer._teleportationRequestInitiated) {
  88762. this._moveTeleportationSelectorTo(hit, gazer);
  88763. }
  88764. return;
  88765. }
  88766. // If not, we're in a selection scenario
  88767. //this._teleportationAllowed = false;
  88768. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88769. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88770. this.onNewMeshPicked.notifyObservers(hit);
  88771. gazer._currentMeshSelected = hit.pickedMesh;
  88772. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88773. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88774. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88775. gazer._isActionableMesh = true;
  88776. }
  88777. else {
  88778. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88779. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88780. gazer._isActionableMesh = false;
  88781. }
  88782. try {
  88783. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88784. }
  88785. catch (err) {
  88786. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88787. }
  88788. }
  88789. else {
  88790. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88791. gazer._currentMeshSelected = null;
  88792. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88793. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88794. }
  88795. }
  88796. }
  88797. else {
  88798. gazer._currentHit = null;
  88799. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88800. gazer._currentMeshSelected = null;
  88801. //this._teleportationAllowed = false;
  88802. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88803. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88804. }
  88805. };
  88806. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88807. if (mesh) {
  88808. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88809. }
  88810. };
  88811. /**
  88812. * Sets the color of the laser ray from the vr controllers.
  88813. * @param color new color for the ray.
  88814. */
  88815. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88816. if (this.leftController) {
  88817. this.leftController._setLaserPointerColor(color);
  88818. }
  88819. if (this.rightController) {
  88820. this.rightController._setLaserPointerColor(color);
  88821. }
  88822. };
  88823. /**
  88824. * Sets the color of the ray from the vr headsets gaze.
  88825. * @param color new color for the ray.
  88826. */
  88827. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88828. if (!this._cameraGazer._gazeTracker.material) {
  88829. return;
  88830. }
  88831. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88832. if (this.leftController) {
  88833. this.leftController._gazeTracker.material.emissiveColor = color;
  88834. }
  88835. if (this.rightController) {
  88836. this.rightController._gazeTracker.material.emissiveColor = color;
  88837. }
  88838. };
  88839. /**
  88840. * Exits VR and disposes of the vr experience helper
  88841. */
  88842. VRExperienceHelper.prototype.dispose = function () {
  88843. if (this.isInVRMode) {
  88844. this.exitVR();
  88845. }
  88846. if (this._postProcessMove) {
  88847. this._postProcessMove.dispose();
  88848. }
  88849. if (this._webVRCamera) {
  88850. this._webVRCamera.dispose();
  88851. }
  88852. if (this._vrDeviceOrientationCamera) {
  88853. this._vrDeviceOrientationCamera.dispose();
  88854. }
  88855. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88856. document.body.removeChild(this._btnVR);
  88857. }
  88858. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88859. this._deviceOrientationCamera.dispose();
  88860. }
  88861. if (this._cameraGazer) {
  88862. this._cameraGazer.dispose();
  88863. }
  88864. if (this.leftController) {
  88865. this.leftController.dispose();
  88866. }
  88867. if (this.rightController) {
  88868. this.rightController.dispose();
  88869. }
  88870. if (this._teleportationTarget) {
  88871. this._teleportationTarget.dispose();
  88872. }
  88873. this._floorMeshesCollection = [];
  88874. document.removeEventListener("keydown", this._onKeyDown);
  88875. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88876. window.removeEventListener("resize", this._onResize);
  88877. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88878. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88879. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88880. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88881. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88882. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88883. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88884. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88885. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88886. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88887. this._scene.unregisterBeforeRender(this.beforeRender);
  88888. };
  88889. /**
  88890. * Gets the name of the VRExperienceHelper class
  88891. * @returns "VRExperienceHelper"
  88892. */
  88893. VRExperienceHelper.prototype.getClassName = function () {
  88894. return "VRExperienceHelper";
  88895. };
  88896. return VRExperienceHelper;
  88897. }());
  88898. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88899. })(BABYLON || (BABYLON = {}));
  88900. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88901. // Mainly based on these 2 articles :
  88902. // 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
  88903. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88904. var BABYLON;
  88905. (function (BABYLON) {
  88906. /**
  88907. * Defines the potential axis of a Joystick
  88908. */
  88909. var JoystickAxis;
  88910. (function (JoystickAxis) {
  88911. /** X axis */
  88912. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88913. /** Y axis */
  88914. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88915. /** Z axis */
  88916. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88917. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88918. /**
  88919. * Class used to define virtual joystick (used in touch mode)
  88920. */
  88921. var VirtualJoystick = /** @class */ (function () {
  88922. /**
  88923. * Creates a new virtual joystick
  88924. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88925. */
  88926. function VirtualJoystick(leftJoystick) {
  88927. var _this = this;
  88928. if (leftJoystick) {
  88929. this._leftJoystick = true;
  88930. }
  88931. else {
  88932. this._leftJoystick = false;
  88933. }
  88934. VirtualJoystick._globalJoystickIndex++;
  88935. // By default left & right arrow keys are moving the X
  88936. // and up & down keys are moving the Y
  88937. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88938. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88939. this.reverseLeftRight = false;
  88940. this.reverseUpDown = false;
  88941. // collections of pointers
  88942. this._touches = new BABYLON.StringDictionary();
  88943. this.deltaPosition = BABYLON.Vector3.Zero();
  88944. this._joystickSensibility = 25;
  88945. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88946. this._onResize = function (evt) {
  88947. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88948. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88949. if (VirtualJoystick.vjCanvas) {
  88950. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88951. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88952. }
  88953. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88954. };
  88955. // injecting a canvas element on top of the canvas 3D game
  88956. if (!VirtualJoystick.vjCanvas) {
  88957. window.addEventListener("resize", this._onResize, false);
  88958. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88959. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88960. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88961. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88962. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88963. VirtualJoystick.vjCanvas.style.width = "100%";
  88964. VirtualJoystick.vjCanvas.style.height = "100%";
  88965. VirtualJoystick.vjCanvas.style.position = "absolute";
  88966. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88967. VirtualJoystick.vjCanvas.style.top = "0px";
  88968. VirtualJoystick.vjCanvas.style.left = "0px";
  88969. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88970. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88971. // Support for jQuery PEP polyfill
  88972. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88973. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88974. if (!context) {
  88975. throw new Error("Unable to create canvas for virtual joystick");
  88976. }
  88977. VirtualJoystick.vjCanvasContext = context;
  88978. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88979. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88980. document.body.appendChild(VirtualJoystick.vjCanvas);
  88981. }
  88982. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88983. this.pressed = false;
  88984. // default joystick color
  88985. this._joystickColor = "cyan";
  88986. this._joystickPointerID = -1;
  88987. // current joystick position
  88988. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88989. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88990. // origin joystick position
  88991. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88992. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88993. this._onPointerDownHandlerRef = function (evt) {
  88994. _this._onPointerDown(evt);
  88995. };
  88996. this._onPointerMoveHandlerRef = function (evt) {
  88997. _this._onPointerMove(evt);
  88998. };
  88999. this._onPointerUpHandlerRef = function (evt) {
  89000. _this._onPointerUp(evt);
  89001. };
  89002. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89003. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89004. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89005. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89006. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89007. evt.preventDefault(); // Disables system menu
  89008. }, false);
  89009. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89010. }
  89011. /**
  89012. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89013. * @param newJoystickSensibility defines the new sensibility
  89014. */
  89015. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89016. this._joystickSensibility = newJoystickSensibility;
  89017. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89018. };
  89019. VirtualJoystick.prototype._onPointerDown = function (e) {
  89020. var positionOnScreenCondition;
  89021. e.preventDefault();
  89022. if (this._leftJoystick === true) {
  89023. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89024. }
  89025. else {
  89026. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89027. }
  89028. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89029. // First contact will be dedicated to the virtual joystick
  89030. this._joystickPointerID = e.pointerId;
  89031. this._joystickPointerStartPos.x = e.clientX;
  89032. this._joystickPointerStartPos.y = e.clientY;
  89033. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89034. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89035. this._deltaJoystickVector.x = 0;
  89036. this._deltaJoystickVector.y = 0;
  89037. this.pressed = true;
  89038. this._touches.add(e.pointerId.toString(), e);
  89039. }
  89040. else {
  89041. // You can only trigger the action buttons with a joystick declared
  89042. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89043. this._action();
  89044. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89045. }
  89046. }
  89047. };
  89048. VirtualJoystick.prototype._onPointerMove = function (e) {
  89049. // If the current pointer is the one associated to the joystick (first touch contact)
  89050. if (this._joystickPointerID == e.pointerId) {
  89051. this._joystickPointerPos.x = e.clientX;
  89052. this._joystickPointerPos.y = e.clientY;
  89053. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89054. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89055. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89056. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89057. switch (this._axisTargetedByLeftAndRight) {
  89058. case JoystickAxis.X:
  89059. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89060. break;
  89061. case JoystickAxis.Y:
  89062. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89063. break;
  89064. case JoystickAxis.Z:
  89065. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89066. break;
  89067. }
  89068. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89069. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89070. switch (this._axisTargetedByUpAndDown) {
  89071. case JoystickAxis.X:
  89072. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89073. break;
  89074. case JoystickAxis.Y:
  89075. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89076. break;
  89077. case JoystickAxis.Z:
  89078. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89079. break;
  89080. }
  89081. }
  89082. else {
  89083. var data = this._touches.get(e.pointerId.toString());
  89084. if (data) {
  89085. data.x = e.clientX;
  89086. data.y = e.clientY;
  89087. }
  89088. }
  89089. };
  89090. VirtualJoystick.prototype._onPointerUp = function (e) {
  89091. if (this._joystickPointerID == e.pointerId) {
  89092. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89093. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89094. this._joystickPointerID = -1;
  89095. this.pressed = false;
  89096. }
  89097. else {
  89098. var touch = this._touches.get(e.pointerId.toString());
  89099. if (touch) {
  89100. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89101. }
  89102. }
  89103. this._deltaJoystickVector.x = 0;
  89104. this._deltaJoystickVector.y = 0;
  89105. this._touches.remove(e.pointerId.toString());
  89106. };
  89107. /**
  89108. * Change the color of the virtual joystick
  89109. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89110. */
  89111. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89112. this._joystickColor = newColor;
  89113. };
  89114. /**
  89115. * Defines a callback to call when the joystick is touched
  89116. * @param action defines the callback
  89117. */
  89118. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89119. this._action = action;
  89120. };
  89121. /**
  89122. * Defines which axis you'd like to control for left & right
  89123. * @param axis defines the axis to use
  89124. */
  89125. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89126. switch (axis) {
  89127. case JoystickAxis.X:
  89128. case JoystickAxis.Y:
  89129. case JoystickAxis.Z:
  89130. this._axisTargetedByLeftAndRight = axis;
  89131. break;
  89132. default:
  89133. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89134. break;
  89135. }
  89136. };
  89137. /**
  89138. * Defines which axis you'd like to control for up & down
  89139. * @param axis defines the axis to use
  89140. */
  89141. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89142. switch (axis) {
  89143. case JoystickAxis.X:
  89144. case JoystickAxis.Y:
  89145. case JoystickAxis.Z:
  89146. this._axisTargetedByUpAndDown = axis;
  89147. break;
  89148. default:
  89149. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89150. break;
  89151. }
  89152. };
  89153. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89154. var _this = this;
  89155. if (this.pressed) {
  89156. this._touches.forEach(function (key, touch) {
  89157. if (touch.pointerId === _this._joystickPointerID) {
  89158. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89159. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89160. VirtualJoystick.vjCanvasContext.beginPath();
  89161. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89162. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89163. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89164. VirtualJoystick.vjCanvasContext.stroke();
  89165. VirtualJoystick.vjCanvasContext.closePath();
  89166. VirtualJoystick.vjCanvasContext.beginPath();
  89167. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89168. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89169. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89170. VirtualJoystick.vjCanvasContext.stroke();
  89171. VirtualJoystick.vjCanvasContext.closePath();
  89172. VirtualJoystick.vjCanvasContext.beginPath();
  89173. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89174. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89175. VirtualJoystick.vjCanvasContext.stroke();
  89176. VirtualJoystick.vjCanvasContext.closePath();
  89177. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89178. }
  89179. else {
  89180. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89181. VirtualJoystick.vjCanvasContext.beginPath();
  89182. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89183. VirtualJoystick.vjCanvasContext.beginPath();
  89184. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89185. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89186. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89187. VirtualJoystick.vjCanvasContext.stroke();
  89188. VirtualJoystick.vjCanvasContext.closePath();
  89189. touch.prevX = touch.x;
  89190. touch.prevY = touch.y;
  89191. }
  89192. ;
  89193. });
  89194. }
  89195. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89196. };
  89197. /**
  89198. * Release internal HTML canvas
  89199. */
  89200. VirtualJoystick.prototype.releaseCanvas = function () {
  89201. if (VirtualJoystick.vjCanvas) {
  89202. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89203. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89204. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89205. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89206. window.removeEventListener("resize", this._onResize);
  89207. document.body.removeChild(VirtualJoystick.vjCanvas);
  89208. VirtualJoystick.vjCanvas = null;
  89209. }
  89210. };
  89211. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89212. VirtualJoystick._globalJoystickIndex = 0;
  89213. return VirtualJoystick;
  89214. }());
  89215. BABYLON.VirtualJoystick = VirtualJoystick;
  89216. })(BABYLON || (BABYLON = {}));
  89217. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89218. var BABYLON;
  89219. (function (BABYLON) {
  89220. // We're mainly based on the logic defined into the FreeCamera code
  89221. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89222. __extends(VirtualJoysticksCamera, _super);
  89223. function VirtualJoysticksCamera(name, position, scene) {
  89224. var _this = _super.call(this, name, position, scene) || this;
  89225. _this.inputs.addVirtualJoystick();
  89226. return _this;
  89227. }
  89228. VirtualJoysticksCamera.prototype.getClassName = function () {
  89229. return "VirtualJoysticksCamera";
  89230. };
  89231. return VirtualJoysticksCamera;
  89232. }(BABYLON.FreeCamera));
  89233. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89234. })(BABYLON || (BABYLON = {}));
  89235. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89236. var BABYLON;
  89237. (function (BABYLON) {
  89238. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89239. function FreeCameraVirtualJoystickInput() {
  89240. }
  89241. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89242. return this._leftjoystick;
  89243. };
  89244. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89245. return this._rightjoystick;
  89246. };
  89247. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89248. if (this._leftjoystick) {
  89249. var camera = this.camera;
  89250. var speed = camera._computeLocalCameraSpeed() * 50;
  89251. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89252. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89253. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89254. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89255. if (!this._leftjoystick.pressed) {
  89256. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89257. }
  89258. if (!this._rightjoystick.pressed) {
  89259. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89260. }
  89261. }
  89262. };
  89263. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89264. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89265. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89266. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89267. this._leftjoystick.setJoystickSensibility(0.15);
  89268. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89269. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89270. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89271. this._rightjoystick.reverseUpDown = true;
  89272. this._rightjoystick.setJoystickSensibility(0.05);
  89273. this._rightjoystick.setJoystickColor("yellow");
  89274. };
  89275. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89276. this._leftjoystick.releaseCanvas();
  89277. this._rightjoystick.releaseCanvas();
  89278. };
  89279. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89280. return "FreeCameraVirtualJoystickInput";
  89281. };
  89282. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89283. return "virtualJoystick";
  89284. };
  89285. return FreeCameraVirtualJoystickInput;
  89286. }());
  89287. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89288. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89289. })(BABYLON || (BABYLON = {}));
  89290. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89291. var BABYLON;
  89292. (function (BABYLON) {
  89293. var SimplificationSettings = /** @class */ (function () {
  89294. function SimplificationSettings(quality, distance, optimizeMesh) {
  89295. this.quality = quality;
  89296. this.distance = distance;
  89297. this.optimizeMesh = optimizeMesh;
  89298. }
  89299. return SimplificationSettings;
  89300. }());
  89301. BABYLON.SimplificationSettings = SimplificationSettings;
  89302. var SimplificationQueue = /** @class */ (function () {
  89303. function SimplificationQueue() {
  89304. this.running = false;
  89305. this._simplificationArray = [];
  89306. }
  89307. SimplificationQueue.prototype.addTask = function (task) {
  89308. this._simplificationArray.push(task);
  89309. };
  89310. SimplificationQueue.prototype.executeNext = function () {
  89311. var task = this._simplificationArray.pop();
  89312. if (task) {
  89313. this.running = true;
  89314. this.runSimplification(task);
  89315. }
  89316. else {
  89317. this.running = false;
  89318. }
  89319. };
  89320. SimplificationQueue.prototype.runSimplification = function (task) {
  89321. var _this = this;
  89322. if (task.parallelProcessing) {
  89323. //parallel simplifier
  89324. task.settings.forEach(function (setting) {
  89325. var simplifier = _this.getSimplifier(task);
  89326. simplifier.simplify(setting, function (newMesh) {
  89327. task.mesh.addLODLevel(setting.distance, newMesh);
  89328. newMesh.isVisible = true;
  89329. //check if it is the last
  89330. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89331. //all done, run the success callback.
  89332. task.successCallback();
  89333. }
  89334. _this.executeNext();
  89335. });
  89336. });
  89337. }
  89338. else {
  89339. //single simplifier.
  89340. var simplifier = this.getSimplifier(task);
  89341. var runDecimation = function (setting, callback) {
  89342. simplifier.simplify(setting, function (newMesh) {
  89343. task.mesh.addLODLevel(setting.distance, newMesh);
  89344. newMesh.isVisible = true;
  89345. //run the next quality level
  89346. callback();
  89347. });
  89348. };
  89349. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89350. runDecimation(task.settings[loop.index], function () {
  89351. loop.executeNext();
  89352. });
  89353. }, function () {
  89354. //execution ended, run the success callback.
  89355. if (task.successCallback) {
  89356. task.successCallback();
  89357. }
  89358. _this.executeNext();
  89359. });
  89360. }
  89361. };
  89362. SimplificationQueue.prototype.getSimplifier = function (task) {
  89363. switch (task.simplificationType) {
  89364. case SimplificationType.QUADRATIC:
  89365. default:
  89366. return new QuadraticErrorSimplification(task.mesh);
  89367. }
  89368. };
  89369. return SimplificationQueue;
  89370. }());
  89371. BABYLON.SimplificationQueue = SimplificationQueue;
  89372. /**
  89373. * The implemented types of simplification
  89374. * At the moment only Quadratic Error Decimation is implemented
  89375. */
  89376. var SimplificationType;
  89377. (function (SimplificationType) {
  89378. /** Quadratic error decimation */
  89379. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89380. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89381. var DecimationTriangle = /** @class */ (function () {
  89382. function DecimationTriangle(vertices) {
  89383. this.vertices = vertices;
  89384. this.error = new Array(4);
  89385. this.deleted = false;
  89386. this.isDirty = false;
  89387. this.deletePending = false;
  89388. this.borderFactor = 0;
  89389. }
  89390. return DecimationTriangle;
  89391. }());
  89392. BABYLON.DecimationTriangle = DecimationTriangle;
  89393. var DecimationVertex = /** @class */ (function () {
  89394. function DecimationVertex(position, id) {
  89395. this.position = position;
  89396. this.id = id;
  89397. this.isBorder = true;
  89398. this.q = new QuadraticMatrix();
  89399. this.triangleCount = 0;
  89400. this.triangleStart = 0;
  89401. this.originalOffsets = [];
  89402. }
  89403. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89404. this.position.copyFrom(newPosition);
  89405. };
  89406. return DecimationVertex;
  89407. }());
  89408. BABYLON.DecimationVertex = DecimationVertex;
  89409. var QuadraticMatrix = /** @class */ (function () {
  89410. function QuadraticMatrix(data) {
  89411. this.data = new Array(10);
  89412. for (var i = 0; i < 10; ++i) {
  89413. if (data && data[i]) {
  89414. this.data[i] = data[i];
  89415. }
  89416. else {
  89417. this.data[i] = 0;
  89418. }
  89419. }
  89420. }
  89421. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89422. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89423. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89424. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89425. return det;
  89426. };
  89427. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89428. for (var i = 0; i < 10; ++i) {
  89429. this.data[i] += matrix.data[i];
  89430. }
  89431. };
  89432. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89433. for (var i = 0; i < 10; ++i) {
  89434. this.data[i] += data[i];
  89435. }
  89436. };
  89437. QuadraticMatrix.prototype.add = function (matrix) {
  89438. var m = new QuadraticMatrix();
  89439. for (var i = 0; i < 10; ++i) {
  89440. m.data[i] = this.data[i] + matrix.data[i];
  89441. }
  89442. return m;
  89443. };
  89444. QuadraticMatrix.FromData = function (a, b, c, d) {
  89445. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89446. };
  89447. //returning an array to avoid garbage collection
  89448. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89449. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89450. };
  89451. return QuadraticMatrix;
  89452. }());
  89453. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89454. var Reference = /** @class */ (function () {
  89455. function Reference(vertexId, triangleId) {
  89456. this.vertexId = vertexId;
  89457. this.triangleId = triangleId;
  89458. }
  89459. return Reference;
  89460. }());
  89461. BABYLON.Reference = Reference;
  89462. /**
  89463. * An implementation of the Quadratic Error simplification algorithm.
  89464. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89465. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89466. * @author RaananW
  89467. */
  89468. var QuadraticErrorSimplification = /** @class */ (function () {
  89469. function QuadraticErrorSimplification(_mesh) {
  89470. this._mesh = _mesh;
  89471. this.syncIterations = 5000;
  89472. this.aggressiveness = 7;
  89473. this.decimationIterations = 100;
  89474. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89475. }
  89476. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89477. var _this = this;
  89478. this.initDecimatedMesh();
  89479. //iterating through the submeshes array, one after the other.
  89480. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89481. _this.initWithMesh(loop.index, function () {
  89482. _this.runDecimation(settings, loop.index, function () {
  89483. loop.executeNext();
  89484. });
  89485. }, settings.optimizeMesh);
  89486. }, function () {
  89487. setTimeout(function () {
  89488. successCallback(_this._reconstructedMesh);
  89489. }, 0);
  89490. });
  89491. };
  89492. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89493. var _this = this;
  89494. var targetCount = ~~(this.triangles.length * settings.quality);
  89495. var deletedTriangles = 0;
  89496. var triangleCount = this.triangles.length;
  89497. var iterationFunction = function (iteration, callback) {
  89498. setTimeout(function () {
  89499. if (iteration % 5 === 0) {
  89500. _this.updateMesh(iteration === 0);
  89501. }
  89502. for (var i = 0; i < _this.triangles.length; ++i) {
  89503. _this.triangles[i].isDirty = false;
  89504. }
  89505. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89506. var trianglesIterator = function (i) {
  89507. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89508. var t = _this.triangles[tIdx];
  89509. if (!t)
  89510. return;
  89511. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89512. return;
  89513. }
  89514. for (var j = 0; j < 3; ++j) {
  89515. if (t.error[j] < threshold) {
  89516. var deleted0 = [];
  89517. var deleted1 = [];
  89518. var v0 = t.vertices[j];
  89519. var v1 = t.vertices[(j + 1) % 3];
  89520. if (v0.isBorder || v1.isBorder)
  89521. continue;
  89522. var p = BABYLON.Vector3.Zero();
  89523. var n = BABYLON.Vector3.Zero();
  89524. var uv = BABYLON.Vector2.Zero();
  89525. var color = new BABYLON.Color4(0, 0, 0, 1);
  89526. _this.calculateError(v0, v1, p, n, uv, color);
  89527. var delTr = new Array();
  89528. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89529. continue;
  89530. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89531. continue;
  89532. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89533. continue;
  89534. var uniqueArray = new Array();
  89535. delTr.forEach(function (deletedT) {
  89536. if (uniqueArray.indexOf(deletedT) === -1) {
  89537. deletedT.deletePending = true;
  89538. uniqueArray.push(deletedT);
  89539. }
  89540. });
  89541. if (uniqueArray.length % 2 !== 0) {
  89542. continue;
  89543. }
  89544. v0.q = v1.q.add(v0.q);
  89545. v0.updatePosition(p);
  89546. var tStart = _this.references.length;
  89547. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89548. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89549. var tCount = _this.references.length - tStart;
  89550. if (tCount <= v0.triangleCount) {
  89551. if (tCount) {
  89552. for (var c = 0; c < tCount; c++) {
  89553. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89554. }
  89555. }
  89556. }
  89557. else {
  89558. v0.triangleStart = tStart;
  89559. }
  89560. v0.triangleCount = tCount;
  89561. break;
  89562. }
  89563. }
  89564. };
  89565. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89566. }, 0);
  89567. };
  89568. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89569. if (triangleCount - deletedTriangles <= targetCount)
  89570. loop.breakLoop();
  89571. else {
  89572. iterationFunction(loop.index, function () {
  89573. loop.executeNext();
  89574. });
  89575. }
  89576. }, function () {
  89577. setTimeout(function () {
  89578. //reconstruct this part of the mesh
  89579. _this.reconstructMesh(submeshIndex);
  89580. successCallback();
  89581. }, 0);
  89582. });
  89583. };
  89584. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89585. var _this = this;
  89586. this.vertices = [];
  89587. this.triangles = [];
  89588. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89589. var indices = this._mesh.getIndices();
  89590. var submesh = this._mesh.subMeshes[submeshIndex];
  89591. var findInVertices = function (positionToSearch) {
  89592. if (optimizeMesh) {
  89593. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89594. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89595. return _this.vertices[ii];
  89596. }
  89597. }
  89598. }
  89599. return null;
  89600. };
  89601. var vertexReferences = [];
  89602. var vertexInit = function (i) {
  89603. if (!positionData) {
  89604. return;
  89605. }
  89606. var offset = i + submesh.verticesStart;
  89607. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89608. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89609. vertex.originalOffsets.push(offset);
  89610. if (vertex.id === _this.vertices.length) {
  89611. _this.vertices.push(vertex);
  89612. }
  89613. vertexReferences.push(vertex.id);
  89614. };
  89615. //var totalVertices = mesh.getTotalVertices();
  89616. var totalVertices = submesh.verticesCount;
  89617. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89618. var indicesInit = function (i) {
  89619. if (!indices) {
  89620. return;
  89621. }
  89622. var offset = (submesh.indexStart / 3) + i;
  89623. var pos = (offset * 3);
  89624. var i0 = indices[pos + 0];
  89625. var i1 = indices[pos + 1];
  89626. var i2 = indices[pos + 2];
  89627. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89628. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89629. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89630. var triangle = new DecimationTriangle([v0, v1, v2]);
  89631. triangle.originalOffset = pos;
  89632. _this.triangles.push(triangle);
  89633. };
  89634. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89635. _this.init(callback);
  89636. });
  89637. });
  89638. };
  89639. QuadraticErrorSimplification.prototype.init = function (callback) {
  89640. var _this = this;
  89641. var triangleInit1 = function (i) {
  89642. var t = _this.triangles[i];
  89643. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89644. for (var j = 0; j < 3; j++) {
  89645. 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))));
  89646. }
  89647. };
  89648. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89649. var triangleInit2 = function (i) {
  89650. var t = _this.triangles[i];
  89651. for (var j = 0; j < 3; ++j) {
  89652. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89653. }
  89654. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89655. };
  89656. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89657. callback();
  89658. });
  89659. });
  89660. };
  89661. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89662. var newTriangles = [];
  89663. var i;
  89664. for (i = 0; i < this.vertices.length; ++i) {
  89665. this.vertices[i].triangleCount = 0;
  89666. }
  89667. var t;
  89668. var j;
  89669. for (i = 0; i < this.triangles.length; ++i) {
  89670. if (!this.triangles[i].deleted) {
  89671. t = this.triangles[i];
  89672. for (j = 0; j < 3; ++j) {
  89673. t.vertices[j].triangleCount = 1;
  89674. }
  89675. newTriangles.push(t);
  89676. }
  89677. }
  89678. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89679. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89680. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89681. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89682. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89683. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89684. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89685. var vertexCount = 0;
  89686. for (i = 0; i < this.vertices.length; ++i) {
  89687. var vertex = this.vertices[i];
  89688. vertex.id = vertexCount;
  89689. if (vertex.triangleCount) {
  89690. vertex.originalOffsets.forEach(function (originalOffset) {
  89691. if (!normalData) {
  89692. return;
  89693. }
  89694. newPositionData.push(vertex.position.x);
  89695. newPositionData.push(vertex.position.y);
  89696. newPositionData.push(vertex.position.z);
  89697. newNormalData.push(normalData[originalOffset * 3]);
  89698. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89699. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89700. if (uvs && uvs.length) {
  89701. newUVsData.push(uvs[(originalOffset * 2)]);
  89702. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89703. }
  89704. else if (colorsData && colorsData.length) {
  89705. newColorsData.push(colorsData[(originalOffset * 4)]);
  89706. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89707. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89708. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89709. }
  89710. ++vertexCount;
  89711. });
  89712. }
  89713. }
  89714. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89715. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89716. var submeshesArray = this._reconstructedMesh.subMeshes;
  89717. this._reconstructedMesh.subMeshes = [];
  89718. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89719. var originalIndices = this._mesh.getIndices();
  89720. for (i = 0; i < newTriangles.length; ++i) {
  89721. t = newTriangles[i]; //now get the new referencing point for each vertex
  89722. [0, 1, 2].forEach(function (idx) {
  89723. var id = originalIndices[t.originalOffset + idx];
  89724. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89725. if (offset < 0)
  89726. offset = 0;
  89727. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89728. });
  89729. }
  89730. //overwriting the old vertex buffers and indices.
  89731. this._reconstructedMesh.setIndices(newIndicesArray);
  89732. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89733. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89734. if (newUVsData.length > 0)
  89735. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89736. if (newColorsData.length > 0)
  89737. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89738. //create submesh
  89739. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89740. if (submeshIndex > 0) {
  89741. this._reconstructedMesh.subMeshes = [];
  89742. submeshesArray.forEach(function (submesh) {
  89743. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89744. });
  89745. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89746. }
  89747. };
  89748. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89749. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89750. this._reconstructedMesh.material = this._mesh.material;
  89751. this._reconstructedMesh.parent = this._mesh.parent;
  89752. this._reconstructedMesh.isVisible = false;
  89753. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89754. };
  89755. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89756. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89757. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89758. if (t.deleted)
  89759. continue;
  89760. var s = this.references[vertex1.triangleStart + i].vertexId;
  89761. var v1 = t.vertices[(s + 1) % 3];
  89762. var v2 = t.vertices[(s + 2) % 3];
  89763. if ((v1 === vertex2 || v2 === vertex2)) {
  89764. deletedArray[i] = true;
  89765. delTr.push(t);
  89766. continue;
  89767. }
  89768. var d1 = v1.position.subtract(point);
  89769. d1 = d1.normalize();
  89770. var d2 = v2.position.subtract(point);
  89771. d2 = d2.normalize();
  89772. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89773. return true;
  89774. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89775. deletedArray[i] = false;
  89776. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89777. return true;
  89778. }
  89779. return false;
  89780. };
  89781. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89782. var newDeleted = deletedTriangles;
  89783. for (var i = 0; i < vertex.triangleCount; ++i) {
  89784. var ref = this.references[vertex.triangleStart + i];
  89785. var t = this.triangles[ref.triangleId];
  89786. if (t.deleted)
  89787. continue;
  89788. if (deletedArray[i] && t.deletePending) {
  89789. t.deleted = true;
  89790. newDeleted++;
  89791. continue;
  89792. }
  89793. t.vertices[ref.vertexId] = origVertex;
  89794. t.isDirty = true;
  89795. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89796. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89797. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89798. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89799. this.references.push(ref);
  89800. }
  89801. return newDeleted;
  89802. };
  89803. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89804. for (var i = 0; i < this.vertices.length; ++i) {
  89805. var vCount = [];
  89806. var vId = [];
  89807. var v = this.vertices[i];
  89808. var j;
  89809. for (j = 0; j < v.triangleCount; ++j) {
  89810. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89811. for (var ii = 0; ii < 3; ii++) {
  89812. var ofs = 0;
  89813. var vv = triangle.vertices[ii];
  89814. while (ofs < vCount.length) {
  89815. if (vId[ofs] === vv.id)
  89816. break;
  89817. ++ofs;
  89818. }
  89819. if (ofs === vCount.length) {
  89820. vCount.push(1);
  89821. vId.push(vv.id);
  89822. }
  89823. else {
  89824. vCount[ofs]++;
  89825. }
  89826. }
  89827. }
  89828. for (j = 0; j < vCount.length; ++j) {
  89829. if (vCount[j] === 1) {
  89830. this.vertices[vId[j]].isBorder = true;
  89831. }
  89832. else {
  89833. this.vertices[vId[j]].isBorder = false;
  89834. }
  89835. }
  89836. }
  89837. };
  89838. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89839. if (identifyBorders === void 0) { identifyBorders = false; }
  89840. var i;
  89841. if (!identifyBorders) {
  89842. var newTrianglesVector = [];
  89843. for (i = 0; i < this.triangles.length; ++i) {
  89844. if (!this.triangles[i].deleted) {
  89845. newTrianglesVector.push(this.triangles[i]);
  89846. }
  89847. }
  89848. this.triangles = newTrianglesVector;
  89849. }
  89850. for (i = 0; i < this.vertices.length; ++i) {
  89851. this.vertices[i].triangleCount = 0;
  89852. this.vertices[i].triangleStart = 0;
  89853. }
  89854. var t;
  89855. var j;
  89856. var v;
  89857. for (i = 0; i < this.triangles.length; ++i) {
  89858. t = this.triangles[i];
  89859. for (j = 0; j < 3; ++j) {
  89860. v = t.vertices[j];
  89861. v.triangleCount++;
  89862. }
  89863. }
  89864. var tStart = 0;
  89865. for (i = 0; i < this.vertices.length; ++i) {
  89866. this.vertices[i].triangleStart = tStart;
  89867. tStart += this.vertices[i].triangleCount;
  89868. this.vertices[i].triangleCount = 0;
  89869. }
  89870. var newReferences = new Array(this.triangles.length * 3);
  89871. for (i = 0; i < this.triangles.length; ++i) {
  89872. t = this.triangles[i];
  89873. for (j = 0; j < 3; ++j) {
  89874. v = t.vertices[j];
  89875. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89876. v.triangleCount++;
  89877. }
  89878. }
  89879. this.references = newReferences;
  89880. if (identifyBorders) {
  89881. this.identifyBorder();
  89882. }
  89883. };
  89884. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89885. var x = point.x;
  89886. var y = point.y;
  89887. var z = point.z;
  89888. 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
  89889. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89890. };
  89891. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89892. var q = vertex1.q.add(vertex2.q);
  89893. var border = vertex1.isBorder && vertex2.isBorder;
  89894. var error = 0;
  89895. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89896. if (qDet !== 0 && !border) {
  89897. if (!pointResult) {
  89898. pointResult = BABYLON.Vector3.Zero();
  89899. }
  89900. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89901. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89902. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89903. error = this.vertexError(q, pointResult);
  89904. }
  89905. else {
  89906. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89907. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89908. var error1 = this.vertexError(q, vertex1.position);
  89909. var error2 = this.vertexError(q, vertex2.position);
  89910. var error3 = this.vertexError(q, p3);
  89911. error = Math.min(error1, error2, error3);
  89912. if (error === error1) {
  89913. if (pointResult) {
  89914. pointResult.copyFrom(vertex1.position);
  89915. }
  89916. }
  89917. else if (error === error2) {
  89918. if (pointResult) {
  89919. pointResult.copyFrom(vertex2.position);
  89920. }
  89921. }
  89922. else {
  89923. if (pointResult) {
  89924. pointResult.copyFrom(p3);
  89925. }
  89926. }
  89927. }
  89928. return error;
  89929. };
  89930. return QuadraticErrorSimplification;
  89931. }());
  89932. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89933. })(BABYLON || (BABYLON = {}));
  89934. //# sourceMappingURL=babylon.meshSimplification.js.map
  89935. var BABYLON;
  89936. (function (BABYLON) {
  89937. var MeshLODLevel = /** @class */ (function () {
  89938. function MeshLODLevel(distance, mesh) {
  89939. this.distance = distance;
  89940. this.mesh = mesh;
  89941. }
  89942. return MeshLODLevel;
  89943. }());
  89944. BABYLON.MeshLODLevel = MeshLODLevel;
  89945. })(BABYLON || (BABYLON = {}));
  89946. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89947. var BABYLON;
  89948. (function (BABYLON) {
  89949. /**
  89950. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89951. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89952. */
  89953. var SceneOptimization = /** @class */ (function () {
  89954. /**
  89955. * Creates the SceneOptimization object
  89956. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89957. * @param desc defines the description associated with the optimization
  89958. */
  89959. function SceneOptimization(
  89960. /**
  89961. * Defines the priority of this optimization (0 by default which means first in the list)
  89962. */
  89963. priority) {
  89964. if (priority === void 0) { priority = 0; }
  89965. this.priority = priority;
  89966. }
  89967. /**
  89968. * Gets a string describing the action executed by the current optimization
  89969. * @returns description string
  89970. */
  89971. SceneOptimization.prototype.getDescription = function () {
  89972. return "";
  89973. };
  89974. /**
  89975. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89976. * @param scene defines the current scene where to apply this optimization
  89977. * @param optimizer defines the current optimizer
  89978. * @returns true if everything that can be done was applied
  89979. */
  89980. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89981. return true;
  89982. };
  89983. ;
  89984. return SceneOptimization;
  89985. }());
  89986. BABYLON.SceneOptimization = SceneOptimization;
  89987. /**
  89988. * Defines an optimization used to reduce the size of render target textures
  89989. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89990. */
  89991. var TextureOptimization = /** @class */ (function (_super) {
  89992. __extends(TextureOptimization, _super);
  89993. /**
  89994. * Creates the TextureOptimization object
  89995. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89996. * @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
  89997. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89998. */
  89999. function TextureOptimization(
  90000. /**
  90001. * Defines the priority of this optimization (0 by default which means first in the list)
  90002. */
  90003. priority,
  90004. /**
  90005. * 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
  90006. */
  90007. maximumSize,
  90008. /**
  90009. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90010. */
  90011. step) {
  90012. if (priority === void 0) { priority = 0; }
  90013. if (maximumSize === void 0) { maximumSize = 1024; }
  90014. if (step === void 0) { step = 0.5; }
  90015. var _this = _super.call(this, priority) || this;
  90016. _this.priority = priority;
  90017. _this.maximumSize = maximumSize;
  90018. _this.step = step;
  90019. return _this;
  90020. }
  90021. /**
  90022. * Gets a string describing the action executed by the current optimization
  90023. * @returns description string
  90024. */
  90025. TextureOptimization.prototype.getDescription = function () {
  90026. return "Reducing render target texture size to " + this.maximumSize;
  90027. };
  90028. /**
  90029. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90030. * @param scene defines the current scene where to apply this optimization
  90031. * @param optimizer defines the current optimizer
  90032. * @returns true if everything that can be done was applied
  90033. */
  90034. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90035. var allDone = true;
  90036. for (var index = 0; index < scene.textures.length; index++) {
  90037. var texture = scene.textures[index];
  90038. if (!texture.canRescale || texture.getContext) {
  90039. continue;
  90040. }
  90041. var currentSize = texture.getSize();
  90042. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90043. if (maxDimension > this.maximumSize) {
  90044. texture.scale(this.step);
  90045. allDone = false;
  90046. }
  90047. }
  90048. return allDone;
  90049. };
  90050. return TextureOptimization;
  90051. }(SceneOptimization));
  90052. BABYLON.TextureOptimization = TextureOptimization;
  90053. /**
  90054. * Defines an optimization used to increase or decrease the rendering resolution
  90055. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90056. */
  90057. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90058. __extends(HardwareScalingOptimization, _super);
  90059. /**
  90060. * Creates the HardwareScalingOptimization object
  90061. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90062. * @param maximumScale defines the maximum scale to use (2 by default)
  90063. * @param step defines the step to use between two passes (0.5 by default)
  90064. */
  90065. function HardwareScalingOptimization(
  90066. /**
  90067. * Defines the priority of this optimization (0 by default which means first in the list)
  90068. */
  90069. priority,
  90070. /**
  90071. * Defines the maximum scale to use (2 by default)
  90072. */
  90073. maximumScale,
  90074. /**
  90075. * Defines the step to use between two passes (0.5 by default)
  90076. */
  90077. step) {
  90078. if (priority === void 0) { priority = 0; }
  90079. if (maximumScale === void 0) { maximumScale = 2; }
  90080. if (step === void 0) { step = 0.25; }
  90081. var _this = _super.call(this, priority) || this;
  90082. _this.priority = priority;
  90083. _this.maximumScale = maximumScale;
  90084. _this.step = step;
  90085. _this._currentScale = -1;
  90086. _this._directionOffset = 1;
  90087. return _this;
  90088. }
  90089. /**
  90090. * Gets a string describing the action executed by the current optimization
  90091. * @return description string
  90092. */
  90093. HardwareScalingOptimization.prototype.getDescription = function () {
  90094. return "Setting hardware scaling level to " + this._currentScale;
  90095. };
  90096. /**
  90097. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90098. * @param scene defines the current scene where to apply this optimization
  90099. * @param optimizer defines the current optimizer
  90100. * @returns true if everything that can be done was applied
  90101. */
  90102. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90103. if (this._currentScale === -1) {
  90104. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90105. if (this._currentScale > this.maximumScale) {
  90106. this._directionOffset = -1;
  90107. }
  90108. }
  90109. this._currentScale += this._directionOffset * this.step;
  90110. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90111. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90112. };
  90113. ;
  90114. return HardwareScalingOptimization;
  90115. }(SceneOptimization));
  90116. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90117. /**
  90118. * Defines an optimization used to remove shadows
  90119. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90120. */
  90121. var ShadowsOptimization = /** @class */ (function (_super) {
  90122. __extends(ShadowsOptimization, _super);
  90123. function ShadowsOptimization() {
  90124. return _super !== null && _super.apply(this, arguments) || this;
  90125. }
  90126. /**
  90127. * Gets a string describing the action executed by the current optimization
  90128. * @return description string
  90129. */
  90130. ShadowsOptimization.prototype.getDescription = function () {
  90131. return "Turning shadows on/off";
  90132. };
  90133. /**
  90134. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90135. * @param scene defines the current scene where to apply this optimization
  90136. * @param optimizer defines the current optimizer
  90137. * @returns true if everything that can be done was applied
  90138. */
  90139. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90140. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90141. return true;
  90142. };
  90143. ;
  90144. return ShadowsOptimization;
  90145. }(SceneOptimization));
  90146. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90147. /**
  90148. * Defines an optimization used to turn post-processes off
  90149. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90150. */
  90151. var PostProcessesOptimization = /** @class */ (function (_super) {
  90152. __extends(PostProcessesOptimization, _super);
  90153. function PostProcessesOptimization() {
  90154. return _super !== null && _super.apply(this, arguments) || this;
  90155. }
  90156. /**
  90157. * Gets a string describing the action executed by the current optimization
  90158. * @return description string
  90159. */
  90160. PostProcessesOptimization.prototype.getDescription = function () {
  90161. return "Turning post-processes on/off";
  90162. };
  90163. /**
  90164. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90165. * @param scene defines the current scene where to apply this optimization
  90166. * @param optimizer defines the current optimizer
  90167. * @returns true if everything that can be done was applied
  90168. */
  90169. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90170. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90171. return true;
  90172. };
  90173. ;
  90174. return PostProcessesOptimization;
  90175. }(SceneOptimization));
  90176. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90177. /**
  90178. * Defines an optimization used to turn lens flares off
  90179. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90180. */
  90181. var LensFlaresOptimization = /** @class */ (function (_super) {
  90182. __extends(LensFlaresOptimization, _super);
  90183. function LensFlaresOptimization() {
  90184. return _super !== null && _super.apply(this, arguments) || this;
  90185. }
  90186. /**
  90187. * Gets a string describing the action executed by the current optimization
  90188. * @return description string
  90189. */
  90190. LensFlaresOptimization.prototype.getDescription = function () {
  90191. return "Turning lens flares on/off";
  90192. };
  90193. /**
  90194. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90195. * @param scene defines the current scene where to apply this optimization
  90196. * @param optimizer defines the current optimizer
  90197. * @returns true if everything that can be done was applied
  90198. */
  90199. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90200. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90201. return true;
  90202. };
  90203. ;
  90204. return LensFlaresOptimization;
  90205. }(SceneOptimization));
  90206. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90207. /**
  90208. * Defines an optimization based on user defined callback.
  90209. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90210. */
  90211. var CustomOptimization = /** @class */ (function (_super) {
  90212. __extends(CustomOptimization, _super);
  90213. function CustomOptimization() {
  90214. return _super !== null && _super.apply(this, arguments) || this;
  90215. }
  90216. /**
  90217. * Gets a string describing the action executed by the current optimization
  90218. * @returns description string
  90219. */
  90220. CustomOptimization.prototype.getDescription = function () {
  90221. if (this.onGetDescription) {
  90222. return this.onGetDescription();
  90223. }
  90224. return "Running user defined callback";
  90225. };
  90226. /**
  90227. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90228. * @param scene defines the current scene where to apply this optimization
  90229. * @param optimizer defines the current optimizer
  90230. * @returns true if everything that can be done was applied
  90231. */
  90232. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90233. if (this.onApply) {
  90234. return this.onApply(scene, optimizer);
  90235. }
  90236. return true;
  90237. };
  90238. ;
  90239. return CustomOptimization;
  90240. }(SceneOptimization));
  90241. BABYLON.CustomOptimization = CustomOptimization;
  90242. /**
  90243. * Defines an optimization used to turn particles off
  90244. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90245. */
  90246. var ParticlesOptimization = /** @class */ (function (_super) {
  90247. __extends(ParticlesOptimization, _super);
  90248. function ParticlesOptimization() {
  90249. return _super !== null && _super.apply(this, arguments) || this;
  90250. }
  90251. /**
  90252. * Gets a string describing the action executed by the current optimization
  90253. * @return description string
  90254. */
  90255. ParticlesOptimization.prototype.getDescription = function () {
  90256. return "Turning particles on/off";
  90257. };
  90258. /**
  90259. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90260. * @param scene defines the current scene where to apply this optimization
  90261. * @param optimizer defines the current optimizer
  90262. * @returns true if everything that can be done was applied
  90263. */
  90264. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90265. scene.particlesEnabled = optimizer.isInImprovementMode;
  90266. return true;
  90267. };
  90268. ;
  90269. return ParticlesOptimization;
  90270. }(SceneOptimization));
  90271. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90272. /**
  90273. * Defines an optimization used to turn render targets off
  90274. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90275. */
  90276. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90277. __extends(RenderTargetsOptimization, _super);
  90278. function RenderTargetsOptimization() {
  90279. return _super !== null && _super.apply(this, arguments) || this;
  90280. }
  90281. /**
  90282. * Gets a string describing the action executed by the current optimization
  90283. * @return description string
  90284. */
  90285. RenderTargetsOptimization.prototype.getDescription = function () {
  90286. return "Turning render targets off";
  90287. };
  90288. /**
  90289. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90290. * @param scene defines the current scene where to apply this optimization
  90291. * @param optimizer defines the current optimizer
  90292. * @returns true if everything that can be done was applied
  90293. */
  90294. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90295. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90296. return true;
  90297. };
  90298. ;
  90299. return RenderTargetsOptimization;
  90300. }(SceneOptimization));
  90301. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90302. /**
  90303. * Defines an optimization used to merge meshes with compatible materials
  90304. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90305. */
  90306. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90307. __extends(MergeMeshesOptimization, _super);
  90308. function MergeMeshesOptimization() {
  90309. var _this = _super !== null && _super.apply(this, arguments) || this;
  90310. _this._canBeMerged = function (abstractMesh) {
  90311. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90312. return false;
  90313. }
  90314. var mesh = abstractMesh;
  90315. if (!mesh.isVisible || !mesh.isEnabled()) {
  90316. return false;
  90317. }
  90318. if (mesh.instances.length > 0) {
  90319. return false;
  90320. }
  90321. if (mesh.skeleton || mesh.hasLODLevels) {
  90322. return false;
  90323. }
  90324. if (mesh.parent) {
  90325. return false;
  90326. }
  90327. return true;
  90328. };
  90329. return _this;
  90330. }
  90331. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90332. /**
  90333. * Gets or sets a boolean which defines if optimization octree has to be updated
  90334. */
  90335. get: function () {
  90336. return MergeMeshesOptimization._UpdateSelectionTree;
  90337. },
  90338. /**
  90339. * Gets or sets a boolean which defines if optimization octree has to be updated
  90340. */
  90341. set: function (value) {
  90342. MergeMeshesOptimization._UpdateSelectionTree = value;
  90343. },
  90344. enumerable: true,
  90345. configurable: true
  90346. });
  90347. /**
  90348. * Gets a string describing the action executed by the current optimization
  90349. * @return description string
  90350. */
  90351. MergeMeshesOptimization.prototype.getDescription = function () {
  90352. return "Merging similar meshes together";
  90353. };
  90354. /**
  90355. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90356. * @param scene defines the current scene where to apply this optimization
  90357. * @param optimizer defines the current optimizer
  90358. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90359. * @returns true if everything that can be done was applied
  90360. */
  90361. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90362. var globalPool = scene.meshes.slice(0);
  90363. var globalLength = globalPool.length;
  90364. for (var index = 0; index < globalLength; index++) {
  90365. var currentPool = new Array();
  90366. var current = globalPool[index];
  90367. // Checks
  90368. if (!this._canBeMerged(current)) {
  90369. continue;
  90370. }
  90371. currentPool.push(current);
  90372. // Find compatible meshes
  90373. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90374. var otherMesh = globalPool[subIndex];
  90375. if (!this._canBeMerged(otherMesh)) {
  90376. continue;
  90377. }
  90378. if (otherMesh.material !== current.material) {
  90379. continue;
  90380. }
  90381. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90382. continue;
  90383. }
  90384. currentPool.push(otherMesh);
  90385. globalLength--;
  90386. globalPool.splice(subIndex, 1);
  90387. subIndex--;
  90388. }
  90389. if (currentPool.length < 2) {
  90390. continue;
  90391. }
  90392. // Merge meshes
  90393. BABYLON.Mesh.MergeMeshes(currentPool);
  90394. }
  90395. if (updateSelectionTree != undefined) {
  90396. if (updateSelectionTree) {
  90397. scene.createOrUpdateSelectionOctree();
  90398. }
  90399. }
  90400. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90401. scene.createOrUpdateSelectionOctree();
  90402. }
  90403. return true;
  90404. };
  90405. ;
  90406. MergeMeshesOptimization._UpdateSelectionTree = false;
  90407. return MergeMeshesOptimization;
  90408. }(SceneOptimization));
  90409. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90410. /**
  90411. * Defines a list of options used by SceneOptimizer
  90412. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90413. */
  90414. var SceneOptimizerOptions = /** @class */ (function () {
  90415. /**
  90416. * Creates a new list of options used by SceneOptimizer
  90417. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90418. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90419. */
  90420. function SceneOptimizerOptions(
  90421. /**
  90422. * Defines the target frame rate to reach (60 by default)
  90423. */
  90424. targetFrameRate,
  90425. /**
  90426. * Defines the interval between two checkes (2000ms by default)
  90427. */
  90428. trackerDuration) {
  90429. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90430. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90431. this.targetFrameRate = targetFrameRate;
  90432. this.trackerDuration = trackerDuration;
  90433. /**
  90434. * Gets the list of optimizations to apply
  90435. */
  90436. this.optimizations = new Array();
  90437. }
  90438. /**
  90439. * Add a new optimization
  90440. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90441. * @returns the current SceneOptimizerOptions
  90442. */
  90443. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90444. this.optimizations.push(optimization);
  90445. return this;
  90446. };
  90447. /**
  90448. * Add a new custom optimization
  90449. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90450. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90451. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90452. * @returns the current SceneOptimizerOptions
  90453. */
  90454. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90455. if (priority === void 0) { priority = 0; }
  90456. var optimization = new CustomOptimization(priority);
  90457. optimization.onApply = onApply;
  90458. optimization.onGetDescription = onGetDescription;
  90459. this.optimizations.push(optimization);
  90460. return this;
  90461. };
  90462. /**
  90463. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90464. * @param targetFrameRate defines the target frame rate (60 by default)
  90465. * @returns a SceneOptimizerOptions object
  90466. */
  90467. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90468. var result = new SceneOptimizerOptions(targetFrameRate);
  90469. var priority = 0;
  90470. result.addOptimization(new MergeMeshesOptimization(priority));
  90471. result.addOptimization(new ShadowsOptimization(priority));
  90472. result.addOptimization(new LensFlaresOptimization(priority));
  90473. // Next priority
  90474. priority++;
  90475. result.addOptimization(new PostProcessesOptimization(priority));
  90476. result.addOptimization(new ParticlesOptimization(priority));
  90477. // Next priority
  90478. priority++;
  90479. result.addOptimization(new TextureOptimization(priority, 1024));
  90480. return result;
  90481. };
  90482. /**
  90483. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90484. * @param targetFrameRate defines the target frame rate (60 by default)
  90485. * @returns a SceneOptimizerOptions object
  90486. */
  90487. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90488. var result = new SceneOptimizerOptions(targetFrameRate);
  90489. var priority = 0;
  90490. result.addOptimization(new MergeMeshesOptimization(priority));
  90491. result.addOptimization(new ShadowsOptimization(priority));
  90492. result.addOptimization(new LensFlaresOptimization(priority));
  90493. // Next priority
  90494. priority++;
  90495. result.addOptimization(new PostProcessesOptimization(priority));
  90496. result.addOptimization(new ParticlesOptimization(priority));
  90497. // Next priority
  90498. priority++;
  90499. result.addOptimization(new TextureOptimization(priority, 512));
  90500. // Next priority
  90501. priority++;
  90502. result.addOptimization(new RenderTargetsOptimization(priority));
  90503. // Next priority
  90504. priority++;
  90505. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90506. return result;
  90507. };
  90508. /**
  90509. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90510. * @param targetFrameRate defines the target frame rate (60 by default)
  90511. * @returns a SceneOptimizerOptions object
  90512. */
  90513. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90514. var result = new SceneOptimizerOptions(targetFrameRate);
  90515. var priority = 0;
  90516. result.addOptimization(new MergeMeshesOptimization(priority));
  90517. result.addOptimization(new ShadowsOptimization(priority));
  90518. result.addOptimization(new LensFlaresOptimization(priority));
  90519. // Next priority
  90520. priority++;
  90521. result.addOptimization(new PostProcessesOptimization(priority));
  90522. result.addOptimization(new ParticlesOptimization(priority));
  90523. // Next priority
  90524. priority++;
  90525. result.addOptimization(new TextureOptimization(priority, 256));
  90526. // Next priority
  90527. priority++;
  90528. result.addOptimization(new RenderTargetsOptimization(priority));
  90529. // Next priority
  90530. priority++;
  90531. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90532. return result;
  90533. };
  90534. return SceneOptimizerOptions;
  90535. }());
  90536. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90537. /**
  90538. * Class used to run optimizations in order to reach a target frame rate
  90539. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90540. */
  90541. var SceneOptimizer = /** @class */ (function () {
  90542. /**
  90543. * Creates a new SceneOptimizer
  90544. * @param scene defines the scene to work on
  90545. * @param options defines the options to use with the SceneOptimizer
  90546. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90547. * @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)
  90548. */
  90549. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90550. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90551. if (improvementMode === void 0) { improvementMode = false; }
  90552. var _this = this;
  90553. this._isRunning = false;
  90554. this._currentPriorityLevel = 0;
  90555. this._targetFrameRate = 60;
  90556. this._trackerDuration = 2000;
  90557. this._currentFrameRate = 0;
  90558. this._improvementMode = false;
  90559. /**
  90560. * Defines an observable called when the optimizer reaches the target frame rate
  90561. */
  90562. this.onSuccessObservable = new BABYLON.Observable();
  90563. /**
  90564. * Defines an observable called when the optimizer enables an optimization
  90565. */
  90566. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90567. /**
  90568. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90569. */
  90570. this.onFailureObservable = new BABYLON.Observable();
  90571. if (!options) {
  90572. this._options = new SceneOptimizerOptions();
  90573. }
  90574. else {
  90575. this._options = options;
  90576. }
  90577. if (this._options.targetFrameRate) {
  90578. this._targetFrameRate = this._options.targetFrameRate;
  90579. }
  90580. if (this._options.trackerDuration) {
  90581. this._trackerDuration = this._options.trackerDuration;
  90582. }
  90583. if (autoGeneratePriorities) {
  90584. var priority = 0;
  90585. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90586. var optim = _a[_i];
  90587. optim.priority = priority++;
  90588. }
  90589. }
  90590. this._improvementMode = improvementMode;
  90591. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90592. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90593. _this._sceneDisposeObserver = null;
  90594. _this.dispose();
  90595. });
  90596. }
  90597. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90598. /**
  90599. * Gets a boolean indicating if the optimizer is in improvement mode
  90600. */
  90601. get: function () {
  90602. return this._improvementMode;
  90603. },
  90604. enumerable: true,
  90605. configurable: true
  90606. });
  90607. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90608. /**
  90609. * Gets the current priority level (0 at start)
  90610. */
  90611. get: function () {
  90612. return this._currentPriorityLevel;
  90613. },
  90614. enumerable: true,
  90615. configurable: true
  90616. });
  90617. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90618. /**
  90619. * Gets the current frame rate checked by the SceneOptimizer
  90620. */
  90621. get: function () {
  90622. return this._currentFrameRate;
  90623. },
  90624. enumerable: true,
  90625. configurable: true
  90626. });
  90627. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90628. /**
  90629. * Gets or sets the current target frame rate (60 by default)
  90630. */
  90631. get: function () {
  90632. return this._targetFrameRate;
  90633. },
  90634. /**
  90635. * Gets or sets the current target frame rate (60 by default)
  90636. */
  90637. set: function (value) {
  90638. this._targetFrameRate = value;
  90639. },
  90640. enumerable: true,
  90641. configurable: true
  90642. });
  90643. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90644. /**
  90645. * Gets or sets the current interval between two checks (every 2000ms by default)
  90646. */
  90647. get: function () {
  90648. return this._trackerDuration;
  90649. },
  90650. /**
  90651. * Gets or sets the current interval between two checks (every 2000ms by default)
  90652. */
  90653. set: function (value) {
  90654. this._trackerDuration = value;
  90655. },
  90656. enumerable: true,
  90657. configurable: true
  90658. });
  90659. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90660. /**
  90661. * Gets the list of active optimizations
  90662. */
  90663. get: function () {
  90664. return this._options.optimizations;
  90665. },
  90666. enumerable: true,
  90667. configurable: true
  90668. });
  90669. /**
  90670. * Stops the current optimizer
  90671. */
  90672. SceneOptimizer.prototype.stop = function () {
  90673. this._isRunning = false;
  90674. };
  90675. /**
  90676. * Reset the optimizer to initial step (current priority level = 0)
  90677. */
  90678. SceneOptimizer.prototype.reset = function () {
  90679. this._currentPriorityLevel = 0;
  90680. };
  90681. /**
  90682. * Start the optimizer. By default it will try to reach a specific framerate
  90683. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90684. */
  90685. SceneOptimizer.prototype.start = function () {
  90686. var _this = this;
  90687. if (this._isRunning) {
  90688. return;
  90689. }
  90690. this._isRunning = true;
  90691. // Let's wait for the scene to be ready before running our check
  90692. this._scene.executeWhenReady(function () {
  90693. setTimeout(function () {
  90694. _this._checkCurrentState();
  90695. }, _this._trackerDuration);
  90696. });
  90697. };
  90698. SceneOptimizer.prototype._checkCurrentState = function () {
  90699. var _this = this;
  90700. if (!this._isRunning) {
  90701. return;
  90702. }
  90703. var scene = this._scene;
  90704. var options = this._options;
  90705. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90706. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90707. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90708. this._isRunning = false;
  90709. this.onSuccessObservable.notifyObservers(this);
  90710. return;
  90711. }
  90712. // Apply current level of optimizations
  90713. var allDone = true;
  90714. var noOptimizationApplied = true;
  90715. for (var index = 0; index < options.optimizations.length; index++) {
  90716. var optimization = options.optimizations[index];
  90717. if (optimization.priority === this._currentPriorityLevel) {
  90718. noOptimizationApplied = false;
  90719. allDone = allDone && optimization.apply(scene, this);
  90720. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90721. }
  90722. }
  90723. // If no optimization was applied, this is a failure :(
  90724. if (noOptimizationApplied) {
  90725. this._isRunning = false;
  90726. this.onFailureObservable.notifyObservers(this);
  90727. return;
  90728. }
  90729. // If all optimizations were done, move to next level
  90730. if (allDone) {
  90731. this._currentPriorityLevel++;
  90732. }
  90733. // Let's the system running for a specific amount of time before checking FPS
  90734. scene.executeWhenReady(function () {
  90735. setTimeout(function () {
  90736. _this._checkCurrentState();
  90737. }, _this._trackerDuration);
  90738. });
  90739. };
  90740. /**
  90741. * Release all resources
  90742. */
  90743. SceneOptimizer.prototype.dispose = function () {
  90744. this.stop();
  90745. this.onSuccessObservable.clear();
  90746. this.onFailureObservable.clear();
  90747. this.onNewOptimizationAppliedObservable.clear();
  90748. if (this._sceneDisposeObserver) {
  90749. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90750. }
  90751. };
  90752. /**
  90753. * Helper function to create a SceneOptimizer with one single line of code
  90754. * @param scene defines the scene to work on
  90755. * @param options defines the options to use with the SceneOptimizer
  90756. * @param onSuccess defines a callback to call on success
  90757. * @param onFailure defines a callback to call on failure
  90758. * @returns the new SceneOptimizer object
  90759. */
  90760. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90761. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90762. if (onSuccess) {
  90763. optimizer.onSuccessObservable.add(function () {
  90764. onSuccess();
  90765. });
  90766. }
  90767. if (onFailure) {
  90768. optimizer.onFailureObservable.add(function () {
  90769. onFailure();
  90770. });
  90771. }
  90772. optimizer.start();
  90773. return optimizer;
  90774. };
  90775. return SceneOptimizer;
  90776. }());
  90777. BABYLON.SceneOptimizer = SceneOptimizer;
  90778. })(BABYLON || (BABYLON = {}));
  90779. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90780. var BABYLON;
  90781. (function (BABYLON) {
  90782. var OutlineRenderer = /** @class */ (function () {
  90783. function OutlineRenderer(scene) {
  90784. this.zOffset = 1;
  90785. this._scene = scene;
  90786. }
  90787. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90788. var _this = this;
  90789. if (useOverlay === void 0) { useOverlay = false; }
  90790. var scene = this._scene;
  90791. var engine = this._scene.getEngine();
  90792. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90793. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90794. return;
  90795. }
  90796. var mesh = subMesh.getRenderingMesh();
  90797. var material = subMesh.getMaterial();
  90798. if (!material || !scene.activeCamera) {
  90799. return;
  90800. }
  90801. engine.enableEffect(this._effect);
  90802. // Logarithmic depth
  90803. if (material.useLogarithmicDepth) {
  90804. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90805. }
  90806. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90807. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90808. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90809. // Bones
  90810. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90811. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90812. }
  90813. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90814. // Alpha test
  90815. if (material && material.needAlphaTesting()) {
  90816. var alphaTexture = material.getAlphaTestTexture();
  90817. if (alphaTexture) {
  90818. this._effect.setTexture("diffuseSampler", alphaTexture);
  90819. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90820. }
  90821. }
  90822. engine.setZOffset(-this.zOffset);
  90823. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90824. engine.setZOffset(0);
  90825. };
  90826. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90827. var defines = [];
  90828. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90829. var mesh = subMesh.getMesh();
  90830. var material = subMesh.getMaterial();
  90831. if (material) {
  90832. // Alpha test
  90833. if (material.needAlphaTesting()) {
  90834. defines.push("#define ALPHATEST");
  90835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90836. attribs.push(BABYLON.VertexBuffer.UVKind);
  90837. defines.push("#define UV1");
  90838. }
  90839. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90840. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90841. defines.push("#define UV2");
  90842. }
  90843. }
  90844. //Logarithmic depth
  90845. if (material.useLogarithmicDepth) {
  90846. defines.push("#define LOGARITHMICDEPTH");
  90847. }
  90848. }
  90849. // Bones
  90850. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90853. if (mesh.numBoneInfluencers > 4) {
  90854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90856. }
  90857. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90858. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90859. }
  90860. else {
  90861. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90862. }
  90863. // Instances
  90864. if (useInstances) {
  90865. defines.push("#define INSTANCES");
  90866. attribs.push("world0");
  90867. attribs.push("world1");
  90868. attribs.push("world2");
  90869. attribs.push("world3");
  90870. }
  90871. // Get correct effect
  90872. var join = defines.join("\n");
  90873. if (this._cachedDefines !== join) {
  90874. this._cachedDefines = join;
  90875. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90876. }
  90877. return this._effect.isReady();
  90878. };
  90879. return OutlineRenderer;
  90880. }());
  90881. BABYLON.OutlineRenderer = OutlineRenderer;
  90882. })(BABYLON || (BABYLON = {}));
  90883. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90884. var BABYLON;
  90885. (function (BABYLON) {
  90886. var FaceAdjacencies = /** @class */ (function () {
  90887. function FaceAdjacencies() {
  90888. this.edges = new Array();
  90889. this.edgesConnectedCount = 0;
  90890. }
  90891. return FaceAdjacencies;
  90892. }());
  90893. var EdgesRenderer = /** @class */ (function () {
  90894. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90895. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90896. if (epsilon === void 0) { epsilon = 0.95; }
  90897. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90898. this.edgesWidthScalerForOrthographic = 1000.0;
  90899. this.edgesWidthScalerForPerspective = 50.0;
  90900. this._linesPositions = new Array();
  90901. this._linesNormals = new Array();
  90902. this._linesIndices = new Array();
  90903. this._buffers = {};
  90904. this._checkVerticesInsteadOfIndices = false;
  90905. this._source = source;
  90906. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90907. this._epsilon = epsilon;
  90908. this._prepareRessources();
  90909. this._generateEdgesLines();
  90910. }
  90911. EdgesRenderer.prototype._prepareRessources = function () {
  90912. if (this._lineShader) {
  90913. return;
  90914. }
  90915. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90916. attributes: ["position", "normal"],
  90917. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90918. });
  90919. this._lineShader.disableDepthWrite = true;
  90920. this._lineShader.backFaceCulling = false;
  90921. };
  90922. EdgesRenderer.prototype._rebuild = function () {
  90923. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90924. if (buffer) {
  90925. buffer._rebuild();
  90926. }
  90927. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90928. if (buffer) {
  90929. buffer._rebuild();
  90930. }
  90931. var scene = this._source.getScene();
  90932. var engine = scene.getEngine();
  90933. this._ib = engine.createIndexBuffer(this._linesIndices);
  90934. };
  90935. EdgesRenderer.prototype.dispose = function () {
  90936. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90937. if (buffer) {
  90938. buffer.dispose();
  90939. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90940. }
  90941. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90942. if (buffer) {
  90943. buffer.dispose();
  90944. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90945. }
  90946. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90947. this._lineShader.dispose();
  90948. };
  90949. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90950. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90951. return 0;
  90952. }
  90953. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90954. return 1;
  90955. }
  90956. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90957. return 2;
  90958. }
  90959. return -1;
  90960. };
  90961. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90962. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90963. return 0;
  90964. }
  90965. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90966. return 1;
  90967. }
  90968. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90969. return 2;
  90970. }
  90971. return -1;
  90972. };
  90973. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90974. var needToCreateLine;
  90975. if (edge === undefined) {
  90976. needToCreateLine = true;
  90977. }
  90978. else {
  90979. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90980. needToCreateLine = dotProduct < this._epsilon;
  90981. }
  90982. if (needToCreateLine) {
  90983. var offset = this._linesPositions.length / 3;
  90984. var normal = p0.subtract(p1);
  90985. normal.normalize();
  90986. // Positions
  90987. this._linesPositions.push(p0.x);
  90988. this._linesPositions.push(p0.y);
  90989. this._linesPositions.push(p0.z);
  90990. this._linesPositions.push(p0.x);
  90991. this._linesPositions.push(p0.y);
  90992. this._linesPositions.push(p0.z);
  90993. this._linesPositions.push(p1.x);
  90994. this._linesPositions.push(p1.y);
  90995. this._linesPositions.push(p1.z);
  90996. this._linesPositions.push(p1.x);
  90997. this._linesPositions.push(p1.y);
  90998. this._linesPositions.push(p1.z);
  90999. // Normals
  91000. this._linesNormals.push(p1.x);
  91001. this._linesNormals.push(p1.y);
  91002. this._linesNormals.push(p1.z);
  91003. this._linesNormals.push(-1);
  91004. this._linesNormals.push(p1.x);
  91005. this._linesNormals.push(p1.y);
  91006. this._linesNormals.push(p1.z);
  91007. this._linesNormals.push(1);
  91008. this._linesNormals.push(p0.x);
  91009. this._linesNormals.push(p0.y);
  91010. this._linesNormals.push(p0.z);
  91011. this._linesNormals.push(-1);
  91012. this._linesNormals.push(p0.x);
  91013. this._linesNormals.push(p0.y);
  91014. this._linesNormals.push(p0.z);
  91015. this._linesNormals.push(1);
  91016. // Indices
  91017. this._linesIndices.push(offset);
  91018. this._linesIndices.push(offset + 1);
  91019. this._linesIndices.push(offset + 2);
  91020. this._linesIndices.push(offset);
  91021. this._linesIndices.push(offset + 2);
  91022. this._linesIndices.push(offset + 3);
  91023. }
  91024. };
  91025. EdgesRenderer.prototype._generateEdgesLines = function () {
  91026. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91027. var indices = this._source.getIndices();
  91028. if (!indices || !positions) {
  91029. return;
  91030. }
  91031. // First let's find adjacencies
  91032. var adjacencies = new Array();
  91033. var faceNormals = new Array();
  91034. var index;
  91035. var faceAdjacencies;
  91036. // Prepare faces
  91037. for (index = 0; index < indices.length; index += 3) {
  91038. faceAdjacencies = new FaceAdjacencies();
  91039. var p0Index = indices[index];
  91040. var p1Index = indices[index + 1];
  91041. var p2Index = indices[index + 2];
  91042. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91043. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91044. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91045. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91046. faceNormal.normalize();
  91047. faceNormals.push(faceNormal);
  91048. adjacencies.push(faceAdjacencies);
  91049. }
  91050. // Scan
  91051. for (index = 0; index < adjacencies.length; index++) {
  91052. faceAdjacencies = adjacencies[index];
  91053. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91054. var otherFaceAdjacencies = adjacencies[otherIndex];
  91055. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91056. break;
  91057. }
  91058. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91059. continue;
  91060. }
  91061. var otherP0 = indices[otherIndex * 3];
  91062. var otherP1 = indices[otherIndex * 3 + 1];
  91063. var otherP2 = indices[otherIndex * 3 + 2];
  91064. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91065. var otherEdgeIndex = 0;
  91066. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91067. continue;
  91068. }
  91069. switch (edgeIndex) {
  91070. case 0:
  91071. if (this._checkVerticesInsteadOfIndices) {
  91072. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91073. }
  91074. else {
  91075. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91076. }
  91077. break;
  91078. case 1:
  91079. if (this._checkVerticesInsteadOfIndices) {
  91080. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91081. }
  91082. else {
  91083. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91084. }
  91085. break;
  91086. case 2:
  91087. if (this._checkVerticesInsteadOfIndices) {
  91088. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91089. }
  91090. else {
  91091. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91092. }
  91093. break;
  91094. }
  91095. if (otherEdgeIndex === -1) {
  91096. continue;
  91097. }
  91098. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91099. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91100. faceAdjacencies.edgesConnectedCount++;
  91101. otherFaceAdjacencies.edgesConnectedCount++;
  91102. if (faceAdjacencies.edgesConnectedCount === 3) {
  91103. break;
  91104. }
  91105. }
  91106. }
  91107. }
  91108. // Create lines
  91109. for (index = 0; index < adjacencies.length; index++) {
  91110. // 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
  91111. var current = adjacencies[index];
  91112. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91113. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91114. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91115. }
  91116. // Merge into a single mesh
  91117. var engine = this._source.getScene().getEngine();
  91118. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91119. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91120. this._ib = engine.createIndexBuffer(this._linesIndices);
  91121. this._indicesCount = this._linesIndices.length;
  91122. };
  91123. EdgesRenderer.prototype.render = function () {
  91124. var scene = this._source.getScene();
  91125. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91126. return;
  91127. }
  91128. var engine = scene.getEngine();
  91129. this._lineShader._preBind();
  91130. // VBOs
  91131. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91132. scene.resetCachedMaterial();
  91133. this._lineShader.setColor4("color", this._source.edgesColor);
  91134. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91135. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91136. }
  91137. else {
  91138. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91139. }
  91140. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91141. this._lineShader.bind(this._source.getWorldMatrix());
  91142. // Draw order
  91143. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91144. this._lineShader.unbind();
  91145. engine.setDepthWrite(true);
  91146. };
  91147. return EdgesRenderer;
  91148. }());
  91149. BABYLON.EdgesRenderer = EdgesRenderer;
  91150. })(BABYLON || (BABYLON = {}));
  91151. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91152. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91153. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91154. s = arguments[i];
  91155. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91156. t[p] = s[p];
  91157. }
  91158. return t;
  91159. };
  91160. var BABYLON;
  91161. (function (BABYLON) {
  91162. /**
  91163. * The effect layer Helps adding post process effect blended with the main pass.
  91164. *
  91165. * This can be for instance use to generate glow or higlight effects on the scene.
  91166. *
  91167. * The effect layer class can not be used directly and is intented to inherited from to be
  91168. * customized per effects.
  91169. */
  91170. var EffectLayer = /** @class */ (function () {
  91171. /**
  91172. * Instantiates a new effect Layer and references it in the scene.
  91173. * @param name The name of the layer
  91174. * @param scene The scene to use the layer in
  91175. */
  91176. function EffectLayer(
  91177. /** The Friendly of the effect in the scene */
  91178. name, scene) {
  91179. this._vertexBuffers = {};
  91180. this._maxSize = 0;
  91181. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91182. this._shouldRender = true;
  91183. this._postProcesses = [];
  91184. this._textures = [];
  91185. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91186. /**
  91187. * The clear color of the texture used to generate the glow map.
  91188. */
  91189. this.neutralColor = new BABYLON.Color4();
  91190. /**
  91191. * Specifies wether the highlight layer is enabled or not.
  91192. */
  91193. this.isEnabled = true;
  91194. /**
  91195. * An event triggered when the effect layer has been disposed.
  91196. */
  91197. this.onDisposeObservable = new BABYLON.Observable();
  91198. /**
  91199. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91200. */
  91201. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91202. /**
  91203. * An event triggered when the generated texture is being merged in the scene.
  91204. */
  91205. this.onBeforeComposeObservable = new BABYLON.Observable();
  91206. /**
  91207. * An event triggered when the generated texture has been merged in the scene.
  91208. */
  91209. this.onAfterComposeObservable = new BABYLON.Observable();
  91210. /**
  91211. * An event triggered when the efffect layer changes its size.
  91212. */
  91213. this.onSizeChangedObservable = new BABYLON.Observable();
  91214. this.name = name;
  91215. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91216. this._engine = scene.getEngine();
  91217. this._maxSize = this._engine.getCaps().maxTextureSize;
  91218. this._scene.effectLayers.push(this);
  91219. // Generate Buffers
  91220. this._generateIndexBuffer();
  91221. this._genrateVertexBuffer();
  91222. }
  91223. Object.defineProperty(EffectLayer.prototype, "camera", {
  91224. /**
  91225. * Gets the camera attached to the layer.
  91226. */
  91227. get: function () {
  91228. return this._effectLayerOptions.camera;
  91229. },
  91230. enumerable: true,
  91231. configurable: true
  91232. });
  91233. /**
  91234. * Initializes the effect layer with the required options.
  91235. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91236. */
  91237. EffectLayer.prototype._init = function (options) {
  91238. // Adapt options
  91239. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91240. this._setMainTextureSize();
  91241. this._createMainTexture();
  91242. this._createTextureAndPostProcesses();
  91243. this._mergeEffect = this._createMergeEffect();
  91244. };
  91245. /**
  91246. * Generates the index buffer of the full screen quad blending to the main canvas.
  91247. */
  91248. EffectLayer.prototype._generateIndexBuffer = function () {
  91249. // Indices
  91250. var indices = [];
  91251. indices.push(0);
  91252. indices.push(1);
  91253. indices.push(2);
  91254. indices.push(0);
  91255. indices.push(2);
  91256. indices.push(3);
  91257. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91258. };
  91259. /**
  91260. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91261. */
  91262. EffectLayer.prototype._genrateVertexBuffer = function () {
  91263. // VBO
  91264. var vertices = [];
  91265. vertices.push(1, 1);
  91266. vertices.push(-1, 1);
  91267. vertices.push(-1, -1);
  91268. vertices.push(1, -1);
  91269. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91271. };
  91272. /**
  91273. * Sets the main texture desired size which is the closest power of two
  91274. * of the engine canvas size.
  91275. */
  91276. EffectLayer.prototype._setMainTextureSize = function () {
  91277. if (this._effectLayerOptions.mainTextureFixedSize) {
  91278. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91279. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91280. }
  91281. else {
  91282. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91283. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91284. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91285. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91286. }
  91287. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91288. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91289. };
  91290. /**
  91291. * Creates the main texture for the effect layer.
  91292. */
  91293. EffectLayer.prototype._createMainTexture = function () {
  91294. var _this = this;
  91295. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91296. width: this._mainTextureDesiredSize.width,
  91297. height: this._mainTextureDesiredSize.height
  91298. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91299. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91300. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91301. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91302. this._mainTexture.anisotropicFilteringLevel = 1;
  91303. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91304. this._mainTexture.renderParticles = false;
  91305. this._mainTexture.renderList = null;
  91306. this._mainTexture.ignoreCameraViewport = true;
  91307. // Custom render function
  91308. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91309. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91310. var index;
  91311. var engine = _this._scene.getEngine();
  91312. if (depthOnlySubMeshes.length) {
  91313. engine.setColorWrite(false);
  91314. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91315. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91316. }
  91317. engine.setColorWrite(true);
  91318. }
  91319. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91320. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91321. }
  91322. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91323. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91324. }
  91325. for (index = 0; index < transparentSubMeshes.length; index++) {
  91326. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91327. }
  91328. };
  91329. this._mainTexture.onClearObservable.add(function (engine) {
  91330. engine.clear(_this.neutralColor, true, true, true);
  91331. });
  91332. };
  91333. /**
  91334. * Checks for the readiness of the element composing the layer.
  91335. * @param subMesh the mesh to check for
  91336. * @param useInstances specify wether or not to use instances to render the mesh
  91337. * @param emissiveTexture the associated emissive texture used to generate the glow
  91338. * @return true if ready otherwise, false
  91339. */
  91340. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91341. var material = subMesh.getMaterial();
  91342. if (!material) {
  91343. return false;
  91344. }
  91345. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91346. return false;
  91347. }
  91348. var defines = [];
  91349. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91350. var mesh = subMesh.getMesh();
  91351. var uv1 = false;
  91352. var uv2 = false;
  91353. // Alpha test
  91354. if (material && material.needAlphaTesting()) {
  91355. var alphaTexture = material.getAlphaTestTexture();
  91356. if (alphaTexture) {
  91357. defines.push("#define ALPHATEST");
  91358. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91359. alphaTexture.coordinatesIndex === 1) {
  91360. defines.push("#define DIFFUSEUV2");
  91361. uv2 = true;
  91362. }
  91363. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91364. defines.push("#define DIFFUSEUV1");
  91365. uv1 = true;
  91366. }
  91367. }
  91368. }
  91369. // Emissive
  91370. if (emissiveTexture) {
  91371. defines.push("#define EMISSIVE");
  91372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91373. emissiveTexture.coordinatesIndex === 1) {
  91374. defines.push("#define EMISSIVEUV2");
  91375. uv2 = true;
  91376. }
  91377. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91378. defines.push("#define EMISSIVEUV1");
  91379. uv1 = true;
  91380. }
  91381. }
  91382. if (uv1) {
  91383. attribs.push(BABYLON.VertexBuffer.UVKind);
  91384. defines.push("#define UV1");
  91385. }
  91386. if (uv2) {
  91387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91388. defines.push("#define UV2");
  91389. }
  91390. // Bones
  91391. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91392. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91393. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91394. if (mesh.numBoneInfluencers > 4) {
  91395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91397. }
  91398. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91399. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91400. }
  91401. else {
  91402. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91403. }
  91404. // Morph targets
  91405. var manager = mesh.morphTargetManager;
  91406. var morphInfluencers = 0;
  91407. if (manager) {
  91408. if (manager.numInfluencers > 0) {
  91409. defines.push("#define MORPHTARGETS");
  91410. morphInfluencers = manager.numInfluencers;
  91411. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91412. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91413. }
  91414. }
  91415. // Instances
  91416. if (useInstances) {
  91417. defines.push("#define INSTANCES");
  91418. attribs.push("world0");
  91419. attribs.push("world1");
  91420. attribs.push("world2");
  91421. attribs.push("world3");
  91422. }
  91423. // Get correct effect
  91424. var join = defines.join("\n");
  91425. if (this._cachedDefines !== join) {
  91426. this._cachedDefines = join;
  91427. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91428. }
  91429. return this._effectLayerMapGenerationEffect.isReady();
  91430. };
  91431. /**
  91432. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91433. */
  91434. EffectLayer.prototype.render = function () {
  91435. var currentEffect = this._mergeEffect;
  91436. // Check
  91437. if (!currentEffect.isReady())
  91438. return;
  91439. for (var i = 0; i < this._postProcesses.length; i++) {
  91440. if (!this._postProcesses[i].isReady()) {
  91441. return;
  91442. }
  91443. }
  91444. var engine = this._scene.getEngine();
  91445. this.onBeforeComposeObservable.notifyObservers(this);
  91446. // Render
  91447. engine.enableEffect(currentEffect);
  91448. engine.setState(false);
  91449. // VBOs
  91450. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91451. // Cache
  91452. var previousAlphaMode = engine.getAlphaMode();
  91453. // Go Blend.
  91454. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91455. // Blends the map on the main canvas.
  91456. this._internalRender(currentEffect);
  91457. // Restore Alpha
  91458. engine.setAlphaMode(previousAlphaMode);
  91459. this.onAfterComposeObservable.notifyObservers(this);
  91460. // Handle size changes.
  91461. var size = this._mainTexture.getSize();
  91462. this._setMainTextureSize();
  91463. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91464. // Recreate RTT and post processes on size change.
  91465. this.onSizeChangedObservable.notifyObservers(this);
  91466. this._disposeTextureAndPostProcesses();
  91467. this._createMainTexture();
  91468. this._createTextureAndPostProcesses();
  91469. }
  91470. };
  91471. /**
  91472. * Determine if a given mesh will be used in the current effect.
  91473. * @param mesh mesh to test
  91474. * @returns true if the mesh will be used
  91475. */
  91476. EffectLayer.prototype.hasMesh = function (mesh) {
  91477. return true;
  91478. };
  91479. /**
  91480. * Returns true if the layer contains information to display, otherwise false.
  91481. * @returns true if the glow layer should be rendered
  91482. */
  91483. EffectLayer.prototype.shouldRender = function () {
  91484. return this.isEnabled && this._shouldRender;
  91485. };
  91486. /**
  91487. * Returns true if the mesh should render, otherwise false.
  91488. * @param mesh The mesh to render
  91489. * @returns true if it should render otherwise false
  91490. */
  91491. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91492. return true;
  91493. };
  91494. /**
  91495. * Returns true if the mesh should render, otherwise false.
  91496. * @param mesh The mesh to render
  91497. * @returns true if it should render otherwise false
  91498. */
  91499. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91500. return true;
  91501. };
  91502. /**
  91503. * Renders the submesh passed in parameter to the generation map.
  91504. */
  91505. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91506. var _this = this;
  91507. if (!this.shouldRender()) {
  91508. return;
  91509. }
  91510. var material = subMesh.getMaterial();
  91511. var mesh = subMesh.getRenderingMesh();
  91512. var scene = this._scene;
  91513. var engine = scene.getEngine();
  91514. if (!material) {
  91515. return;
  91516. }
  91517. // Do not block in blend mode.
  91518. if (material.needAlphaBlendingForMesh(mesh)) {
  91519. return;
  91520. }
  91521. // Culling
  91522. engine.setState(material.backFaceCulling);
  91523. // Managing instances
  91524. var batch = mesh._getInstancesRenderList(subMesh._id);
  91525. if (batch.mustReturn) {
  91526. return;
  91527. }
  91528. // Early Exit per mesh
  91529. if (!this._shouldRenderMesh(mesh)) {
  91530. return;
  91531. }
  91532. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91533. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91534. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91535. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91536. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91537. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91538. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91539. // Alpha test
  91540. if (material && material.needAlphaTesting()) {
  91541. var alphaTexture = material.getAlphaTestTexture();
  91542. if (alphaTexture) {
  91543. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91544. var textureMatrix = alphaTexture.getTextureMatrix();
  91545. if (textureMatrix) {
  91546. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91547. }
  91548. }
  91549. }
  91550. // Glow emissive only
  91551. if (this._emissiveTextureAndColor.texture) {
  91552. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91553. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91554. }
  91555. // Bones
  91556. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91557. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91558. }
  91559. // Morph targets
  91560. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91561. // Draw
  91562. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91563. }
  91564. else {
  91565. // Need to reset refresh rate of the shadowMap
  91566. this._mainTexture.resetRefreshCounter();
  91567. }
  91568. };
  91569. /**
  91570. * Rebuild the required buffers.
  91571. * @hidden Internal use only.
  91572. */
  91573. EffectLayer.prototype._rebuild = function () {
  91574. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91575. if (vb) {
  91576. vb._rebuild();
  91577. }
  91578. this._generateIndexBuffer();
  91579. };
  91580. /**
  91581. * Dispose only the render target textures and post process.
  91582. */
  91583. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91584. this._mainTexture.dispose();
  91585. for (var i = 0; i < this._postProcesses.length; i++) {
  91586. if (this._postProcesses[i]) {
  91587. this._postProcesses[i].dispose();
  91588. }
  91589. }
  91590. this._postProcesses = [];
  91591. for (var i = 0; i < this._textures.length; i++) {
  91592. if (this._textures[i]) {
  91593. this._textures[i].dispose();
  91594. }
  91595. }
  91596. this._textures = [];
  91597. };
  91598. /**
  91599. * Dispose the highlight layer and free resources.
  91600. */
  91601. EffectLayer.prototype.dispose = function () {
  91602. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91603. if (vertexBuffer) {
  91604. vertexBuffer.dispose();
  91605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91606. }
  91607. if (this._indexBuffer) {
  91608. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91609. this._indexBuffer = null;
  91610. }
  91611. // Clean textures and post processes
  91612. this._disposeTextureAndPostProcesses();
  91613. // Remove from scene
  91614. var index = this._scene.effectLayers.indexOf(this, 0);
  91615. if (index > -1) {
  91616. this._scene.effectLayers.splice(index, 1);
  91617. }
  91618. // Callback
  91619. this.onDisposeObservable.notifyObservers(this);
  91620. this.onDisposeObservable.clear();
  91621. this.onBeforeRenderMainTextureObservable.clear();
  91622. this.onBeforeComposeObservable.clear();
  91623. this.onAfterComposeObservable.clear();
  91624. this.onSizeChangedObservable.clear();
  91625. };
  91626. /**
  91627. * Gets the class name of the effect layer
  91628. * @returns the string with the class name of the effect layer
  91629. */
  91630. EffectLayer.prototype.getClassName = function () {
  91631. return "EffectLayer";
  91632. };
  91633. /**
  91634. * Creates an effect layer from parsed effect layer data
  91635. * @param parsedEffectLayer defines effect layer data
  91636. * @param scene defines the current scene
  91637. * @param rootUrl defines the root URL containing the effect layer information
  91638. * @returns a parsed effect Layer
  91639. */
  91640. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91641. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91642. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91643. };
  91644. __decorate([
  91645. BABYLON.serialize()
  91646. ], EffectLayer.prototype, "name", void 0);
  91647. __decorate([
  91648. BABYLON.serializeAsColor4()
  91649. ], EffectLayer.prototype, "neutralColor", void 0);
  91650. __decorate([
  91651. BABYLON.serialize()
  91652. ], EffectLayer.prototype, "isEnabled", void 0);
  91653. __decorate([
  91654. BABYLON.serializeAsCameraReference()
  91655. ], EffectLayer.prototype, "camera", null);
  91656. return EffectLayer;
  91657. }());
  91658. BABYLON.EffectLayer = EffectLayer;
  91659. })(BABYLON || (BABYLON = {}));
  91660. //# sourceMappingURL=babylon.effectLayer.js.map
  91661. var BABYLON;
  91662. (function (BABYLON) {
  91663. /**
  91664. * Special Glow Blur post process only blurring the alpha channel
  91665. * It enforces keeping the most luminous color in the color channel.
  91666. */
  91667. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91668. __extends(GlowBlurPostProcess, _super);
  91669. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91671. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91672. _this.direction = direction;
  91673. _this.kernel = kernel;
  91674. _this.onApplyObservable.add(function (effect) {
  91675. effect.setFloat2("screenSize", _this.width, _this.height);
  91676. effect.setVector2("direction", _this.direction);
  91677. effect.setFloat("blurWidth", _this.kernel);
  91678. });
  91679. return _this;
  91680. }
  91681. return GlowBlurPostProcess;
  91682. }(BABYLON.PostProcess));
  91683. /**
  91684. * The highlight layer Helps adding a glow effect around a mesh.
  91685. *
  91686. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91687. * glowy meshes to your scene.
  91688. *
  91689. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91690. */
  91691. var HighlightLayer = /** @class */ (function (_super) {
  91692. __extends(HighlightLayer, _super);
  91693. /**
  91694. * Instantiates a new highlight Layer and references it to the scene..
  91695. * @param name The name of the layer
  91696. * @param scene The scene to use the layer in
  91697. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91698. */
  91699. function HighlightLayer(name, scene, options) {
  91700. var _this = _super.call(this, name, scene) || this;
  91701. _this.name = name;
  91702. /**
  91703. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91704. */
  91705. _this.innerGlow = true;
  91706. /**
  91707. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91708. */
  91709. _this.outerGlow = true;
  91710. /**
  91711. * An event triggered when the highlight layer is being blurred.
  91712. */
  91713. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91714. /**
  91715. * An event triggered when the highlight layer has been blurred.
  91716. */
  91717. _this.onAfterBlurObservable = new BABYLON.Observable();
  91718. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91719. _this._meshes = {};
  91720. _this._excludedMeshes = {};
  91721. _this.neutralColor = HighlightLayer.NeutralColor;
  91722. // Warn on stencil
  91723. if (!_this._engine.isStencilEnable) {
  91724. 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 }");
  91725. }
  91726. // Adapt options
  91727. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91728. // Initialize the layer
  91729. _this._init({
  91730. alphaBlendingMode: _this._options.alphaBlendingMode,
  91731. camera: _this._options.camera,
  91732. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91733. mainTextureRatio: _this._options.mainTextureRatio
  91734. });
  91735. // Do not render as long as no meshes have been added
  91736. _this._shouldRender = false;
  91737. return _this;
  91738. }
  91739. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91740. /**
  91741. * Gets the horizontal size of the blur.
  91742. */
  91743. get: function () {
  91744. return this._horizontalBlurPostprocess.kernel;
  91745. },
  91746. /**
  91747. * Specifies the horizontal size of the blur.
  91748. */
  91749. set: function (value) {
  91750. this._horizontalBlurPostprocess.kernel = value;
  91751. },
  91752. enumerable: true,
  91753. configurable: true
  91754. });
  91755. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91756. /**
  91757. * Gets the vertical size of the blur.
  91758. */
  91759. get: function () {
  91760. return this._verticalBlurPostprocess.kernel;
  91761. },
  91762. /**
  91763. * Specifies the vertical size of the blur.
  91764. */
  91765. set: function (value) {
  91766. this._verticalBlurPostprocess.kernel = value;
  91767. },
  91768. enumerable: true,
  91769. configurable: true
  91770. });
  91771. /**
  91772. * Get the effect name of the layer.
  91773. * @return The effect name
  91774. */
  91775. HighlightLayer.prototype.getEffectName = function () {
  91776. return HighlightLayer.EffectName;
  91777. };
  91778. /**
  91779. * Create the merge effect. This is the shader use to blit the information back
  91780. * to the main canvas at the end of the scene rendering.
  91781. */
  91782. HighlightLayer.prototype._createMergeEffect = function () {
  91783. // Effect
  91784. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91785. };
  91786. /**
  91787. * Creates the render target textures and post processes used in the highlight layer.
  91788. */
  91789. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91790. var _this = this;
  91791. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91792. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91793. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91794. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91795. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91796. width: blurTextureWidth,
  91797. height: blurTextureHeight
  91798. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91799. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91800. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91801. this._blurTexture.anisotropicFilteringLevel = 16;
  91802. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91803. this._blurTexture.renderParticles = false;
  91804. this._blurTexture.ignoreCameraViewport = true;
  91805. this._textures = [this._blurTexture];
  91806. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91807. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91808. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91809. effect.setTexture("textureSampler", _this._mainTexture);
  91810. });
  91811. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91812. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91813. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91814. });
  91815. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91816. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91817. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91818. });
  91819. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91820. }
  91821. else {
  91822. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91823. width: blurTextureWidth,
  91824. height: blurTextureHeight
  91825. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91826. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91827. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91828. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91829. effect.setTexture("textureSampler", _this._mainTexture);
  91830. });
  91831. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91832. width: blurTextureWidth,
  91833. height: blurTextureHeight
  91834. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91835. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91836. }
  91837. this._mainTexture.onAfterUnbindObservable.add(function () {
  91838. _this.onBeforeBlurObservable.notifyObservers(_this);
  91839. var internalTexture = _this._blurTexture.getInternalTexture();
  91840. if (internalTexture) {
  91841. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91842. }
  91843. _this.onAfterBlurObservable.notifyObservers(_this);
  91844. });
  91845. // Prevent autoClear.
  91846. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91847. };
  91848. /**
  91849. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91850. */
  91851. HighlightLayer.prototype.needStencil = function () {
  91852. return true;
  91853. };
  91854. /**
  91855. * Checks for the readiness of the element composing the layer.
  91856. * @param subMesh the mesh to check for
  91857. * @param useInstances specify wether or not to use instances to render the mesh
  91858. * @param emissiveTexture the associated emissive texture used to generate the glow
  91859. * @return true if ready otherwise, false
  91860. */
  91861. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91862. var material = subMesh.getMaterial();
  91863. var mesh = subMesh.getRenderingMesh();
  91864. if (!material || !mesh || !this._meshes) {
  91865. return false;
  91866. }
  91867. var emissiveTexture = null;
  91868. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91869. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91870. emissiveTexture = material.emissiveTexture;
  91871. }
  91872. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91873. };
  91874. /**
  91875. * Implementation specific of rendering the generating effect on the main canvas.
  91876. * @param effect The effect used to render through
  91877. */
  91878. HighlightLayer.prototype._internalRender = function (effect) {
  91879. // Texture
  91880. effect.setTexture("textureSampler", this._blurTexture);
  91881. // Cache
  91882. var engine = this._engine;
  91883. var previousStencilBuffer = engine.getStencilBuffer();
  91884. var previousStencilFunction = engine.getStencilFunction();
  91885. var previousStencilMask = engine.getStencilMask();
  91886. var previousStencilOperationPass = engine.getStencilOperationPass();
  91887. var previousStencilOperationFail = engine.getStencilOperationFail();
  91888. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91889. var previousStencilReference = engine.getStencilFunctionReference();
  91890. // Stencil operations
  91891. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91892. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91893. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91894. // Draw order
  91895. engine.setStencilMask(0x00);
  91896. engine.setStencilBuffer(true);
  91897. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91898. // 2 passes inner outer
  91899. if (this.outerGlow) {
  91900. effect.setFloat("offset", 0);
  91901. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91902. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91903. }
  91904. if (this.innerGlow) {
  91905. effect.setFloat("offset", 1);
  91906. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91908. }
  91909. // Restore Cache
  91910. engine.setStencilFunction(previousStencilFunction);
  91911. engine.setStencilMask(previousStencilMask);
  91912. engine.setStencilBuffer(previousStencilBuffer);
  91913. engine.setStencilOperationPass(previousStencilOperationPass);
  91914. engine.setStencilOperationFail(previousStencilOperationFail);
  91915. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91916. engine.setStencilFunctionReference(previousStencilReference);
  91917. };
  91918. /**
  91919. * Returns true if the layer contains information to display, otherwise false.
  91920. */
  91921. HighlightLayer.prototype.shouldRender = function () {
  91922. if (_super.prototype.shouldRender.call(this)) {
  91923. return this._meshes ? true : false;
  91924. }
  91925. return false;
  91926. };
  91927. /**
  91928. * Returns true if the mesh should render, otherwise false.
  91929. * @param mesh The mesh to render
  91930. * @returns true if it should render otherwise false
  91931. */
  91932. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91933. // Excluded Mesh
  91934. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91935. return false;
  91936. }
  91937. ;
  91938. return true;
  91939. };
  91940. /**
  91941. * Sets the required values for both the emissive texture and and the main color.
  91942. */
  91943. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91944. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91945. if (highlightLayerMesh) {
  91946. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91947. }
  91948. else {
  91949. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91950. }
  91951. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91952. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91953. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91954. }
  91955. else {
  91956. this._emissiveTextureAndColor.texture = null;
  91957. }
  91958. };
  91959. /**
  91960. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91961. * @param mesh The mesh to exclude from the highlight layer
  91962. */
  91963. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91964. if (!this._excludedMeshes) {
  91965. return;
  91966. }
  91967. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91968. if (!meshExcluded) {
  91969. this._excludedMeshes[mesh.uniqueId] = {
  91970. mesh: mesh,
  91971. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91972. mesh.getEngine().setStencilBuffer(false);
  91973. }),
  91974. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91975. mesh.getEngine().setStencilBuffer(true);
  91976. }),
  91977. };
  91978. }
  91979. };
  91980. /**
  91981. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91982. * @param mesh The mesh to highlight
  91983. */
  91984. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91985. if (!this._excludedMeshes) {
  91986. return;
  91987. }
  91988. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91989. if (meshExcluded) {
  91990. if (meshExcluded.beforeRender) {
  91991. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91992. }
  91993. if (meshExcluded.afterRender) {
  91994. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91995. }
  91996. }
  91997. this._excludedMeshes[mesh.uniqueId] = null;
  91998. };
  91999. /**
  92000. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92001. * @param mesh mesh to test
  92002. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92003. */
  92004. HighlightLayer.prototype.hasMesh = function (mesh) {
  92005. if (!this._meshes) {
  92006. return false;
  92007. }
  92008. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92009. };
  92010. /**
  92011. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92012. * @param mesh The mesh to highlight
  92013. * @param color The color of the highlight
  92014. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92015. */
  92016. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92017. var _this = this;
  92018. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92019. if (!this._meshes) {
  92020. return;
  92021. }
  92022. var meshHighlight = this._meshes[mesh.uniqueId];
  92023. if (meshHighlight) {
  92024. meshHighlight.color = color;
  92025. }
  92026. else {
  92027. this._meshes[mesh.uniqueId] = {
  92028. mesh: mesh,
  92029. color: color,
  92030. // Lambda required for capture due to Observable this context
  92031. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92032. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92033. _this._defaultStencilReference(mesh);
  92034. }
  92035. else {
  92036. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92037. }
  92038. }),
  92039. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92040. glowEmissiveOnly: glowEmissiveOnly
  92041. };
  92042. }
  92043. this._shouldRender = true;
  92044. };
  92045. /**
  92046. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92047. * @param mesh The mesh to highlight
  92048. */
  92049. HighlightLayer.prototype.removeMesh = function (mesh) {
  92050. if (!this._meshes) {
  92051. return;
  92052. }
  92053. var meshHighlight = this._meshes[mesh.uniqueId];
  92054. if (meshHighlight) {
  92055. if (meshHighlight.observerHighlight) {
  92056. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92057. }
  92058. if (meshHighlight.observerDefault) {
  92059. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92060. }
  92061. delete this._meshes[mesh.uniqueId];
  92062. }
  92063. this._shouldRender = false;
  92064. for (var meshHighlightToCheck in this._meshes) {
  92065. if (this._meshes[meshHighlightToCheck]) {
  92066. this._shouldRender = true;
  92067. break;
  92068. }
  92069. }
  92070. };
  92071. /**
  92072. * Force the stencil to the normal expected value for none glowing parts
  92073. */
  92074. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92075. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92076. };
  92077. /**
  92078. * Free any resources and references associated to a mesh.
  92079. * Internal use
  92080. * @param mesh The mesh to free.
  92081. */
  92082. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92083. this.removeMesh(mesh);
  92084. this.removeExcludedMesh(mesh);
  92085. };
  92086. /**
  92087. * Dispose the highlight layer and free resources.
  92088. */
  92089. HighlightLayer.prototype.dispose = function () {
  92090. if (this._meshes) {
  92091. // Clean mesh references
  92092. for (var id in this._meshes) {
  92093. var meshHighlight = this._meshes[id];
  92094. if (meshHighlight && meshHighlight.mesh) {
  92095. if (meshHighlight.observerHighlight) {
  92096. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92097. }
  92098. if (meshHighlight.observerDefault) {
  92099. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92100. }
  92101. }
  92102. }
  92103. this._meshes = null;
  92104. }
  92105. if (this._excludedMeshes) {
  92106. for (var id in this._excludedMeshes) {
  92107. var meshHighlight = this._excludedMeshes[id];
  92108. if (meshHighlight) {
  92109. if (meshHighlight.beforeRender) {
  92110. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92111. }
  92112. if (meshHighlight.afterRender) {
  92113. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92114. }
  92115. }
  92116. }
  92117. this._excludedMeshes = null;
  92118. }
  92119. _super.prototype.dispose.call(this);
  92120. };
  92121. /**
  92122. * Gets the class name of the effect layer
  92123. * @returns the string with the class name of the effect layer
  92124. */
  92125. HighlightLayer.prototype.getClassName = function () {
  92126. return "HighlightLayer";
  92127. };
  92128. /**
  92129. * Serializes this Highlight layer
  92130. * @returns a serialized Highlight layer object
  92131. */
  92132. HighlightLayer.prototype.serialize = function () {
  92133. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92134. serializationObject.customType = "BABYLON.HighlightLayer";
  92135. // Highlighted meshes
  92136. serializationObject.meshes = [];
  92137. if (this._meshes) {
  92138. for (var m in this._meshes) {
  92139. var mesh = this._meshes[m];
  92140. if (mesh) {
  92141. serializationObject.meshes.push({
  92142. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92143. color: mesh.color.asArray(),
  92144. meshId: mesh.mesh.id
  92145. });
  92146. }
  92147. }
  92148. }
  92149. // Excluded meshes
  92150. serializationObject.excludedMeshes = [];
  92151. if (this._excludedMeshes) {
  92152. for (var e in this._excludedMeshes) {
  92153. var excludedMesh = this._excludedMeshes[e];
  92154. if (excludedMesh) {
  92155. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92156. }
  92157. }
  92158. }
  92159. return serializationObject;
  92160. };
  92161. /**
  92162. * Creates a Highlight layer from parsed Highlight layer data
  92163. * @param parsedHightlightLayer defines the Highlight layer data
  92164. * @param scene defines the current scene
  92165. * @param rootUrl defines the root URL containing the Highlight layer information
  92166. * @returns a parsed Highlight layer
  92167. */
  92168. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92169. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92170. var index;
  92171. // Excluded meshes
  92172. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92173. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92174. if (mesh) {
  92175. hl.addExcludedMesh(mesh);
  92176. }
  92177. }
  92178. // Included meshes
  92179. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92180. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92181. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92182. if (mesh) {
  92183. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92184. }
  92185. }
  92186. return hl;
  92187. };
  92188. /**
  92189. * Effect Name of the highlight layer.
  92190. */
  92191. HighlightLayer.EffectName = "HighlightLayer";
  92192. /**
  92193. * The neutral color used during the preparation of the glow effect.
  92194. * This is black by default as the blend operation is a blend operation.
  92195. */
  92196. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92197. /**
  92198. * Stencil value used for glowing meshes.
  92199. */
  92200. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92201. /**
  92202. * Stencil value used for the other meshes in the scene.
  92203. */
  92204. HighlightLayer.NormalMeshStencilReference = 0x01;
  92205. __decorate([
  92206. BABYLON.serialize()
  92207. ], HighlightLayer.prototype, "innerGlow", void 0);
  92208. __decorate([
  92209. BABYLON.serialize()
  92210. ], HighlightLayer.prototype, "outerGlow", void 0);
  92211. __decorate([
  92212. BABYLON.serialize()
  92213. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92214. __decorate([
  92215. BABYLON.serialize()
  92216. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92217. __decorate([
  92218. BABYLON.serialize("options")
  92219. ], HighlightLayer.prototype, "_options", void 0);
  92220. return HighlightLayer;
  92221. }(BABYLON.EffectLayer));
  92222. BABYLON.HighlightLayer = HighlightLayer;
  92223. })(BABYLON || (BABYLON = {}));
  92224. //# sourceMappingURL=babylon.highlightLayer.js.map
  92225. var BABYLON;
  92226. (function (BABYLON) {
  92227. /**
  92228. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92229. *
  92230. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92231. * glowy meshes to your scene.
  92232. *
  92233. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92234. */
  92235. var GlowLayer = /** @class */ (function (_super) {
  92236. __extends(GlowLayer, _super);
  92237. /**
  92238. * Instantiates a new glow Layer and references it to the scene.
  92239. * @param name The name of the layer
  92240. * @param scene The scene to use the layer in
  92241. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92242. */
  92243. function GlowLayer(name, scene, options) {
  92244. var _this = _super.call(this, name, scene) || this;
  92245. _this._intensity = 1.0;
  92246. _this._includedOnlyMeshes = [];
  92247. _this._excludedMeshes = [];
  92248. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92249. // Adapt options
  92250. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92251. // Initialize the layer
  92252. _this._init({
  92253. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92254. camera: _this._options.camera,
  92255. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92256. mainTextureRatio: _this._options.mainTextureRatio
  92257. });
  92258. return _this;
  92259. }
  92260. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92261. /**
  92262. * Gets the kernel size of the blur.
  92263. */
  92264. get: function () {
  92265. return this._horizontalBlurPostprocess1.kernel;
  92266. },
  92267. /**
  92268. * Sets the kernel size of the blur.
  92269. */
  92270. set: function (value) {
  92271. this._horizontalBlurPostprocess1.kernel = value;
  92272. this._verticalBlurPostprocess1.kernel = value;
  92273. this._horizontalBlurPostprocess2.kernel = value;
  92274. this._verticalBlurPostprocess2.kernel = value;
  92275. },
  92276. enumerable: true,
  92277. configurable: true
  92278. });
  92279. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92280. /**
  92281. * Gets the glow intensity.
  92282. */
  92283. get: function () {
  92284. return this._intensity;
  92285. },
  92286. /**
  92287. * Sets the glow intensity.
  92288. */
  92289. set: function (value) {
  92290. this._intensity = value;
  92291. },
  92292. enumerable: true,
  92293. configurable: true
  92294. });
  92295. /**
  92296. * Get the effect name of the layer.
  92297. * @return The effect name
  92298. */
  92299. GlowLayer.prototype.getEffectName = function () {
  92300. return GlowLayer.EffectName;
  92301. };
  92302. /**
  92303. * Create the merge effect. This is the shader use to blit the information back
  92304. * to the main canvas at the end of the scene rendering.
  92305. */
  92306. GlowLayer.prototype._createMergeEffect = function () {
  92307. // Effect
  92308. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92309. };
  92310. /**
  92311. * Creates the render target textures and post processes used in the glow layer.
  92312. */
  92313. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92314. var _this = this;
  92315. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92316. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92317. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92318. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92319. var textureType = 0;
  92320. if (this._engine.getCaps().textureHalfFloatRender) {
  92321. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92322. }
  92323. else {
  92324. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92325. }
  92326. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92327. width: blurTextureWidth,
  92328. height: blurTextureHeight
  92329. }, this._scene, false, true, textureType);
  92330. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92331. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92332. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92333. this._blurTexture1.renderParticles = false;
  92334. this._blurTexture1.ignoreCameraViewport = true;
  92335. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92336. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92337. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92338. width: blurTextureWidth2,
  92339. height: blurTextureHeight2
  92340. }, this._scene, false, true, textureType);
  92341. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92342. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92343. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92344. this._blurTexture2.renderParticles = false;
  92345. this._blurTexture2.ignoreCameraViewport = true;
  92346. this._textures = [this._blurTexture1, this._blurTexture2];
  92347. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92348. width: blurTextureWidth,
  92349. height: blurTextureHeight
  92350. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92351. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92352. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92353. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92354. effect.setTexture("textureSampler", _this._mainTexture);
  92355. });
  92356. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92357. width: blurTextureWidth,
  92358. height: blurTextureHeight
  92359. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92360. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92361. width: blurTextureWidth2,
  92362. height: blurTextureHeight2
  92363. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92364. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92365. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92366. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92367. effect.setTexture("textureSampler", _this._blurTexture1);
  92368. });
  92369. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92370. width: blurTextureWidth2,
  92371. height: blurTextureHeight2
  92372. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92373. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92374. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92375. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92376. this._mainTexture.samples = this._options.mainTextureSamples;
  92377. this._mainTexture.onAfterUnbindObservable.add(function () {
  92378. var internalTexture = _this._blurTexture1.getInternalTexture();
  92379. if (internalTexture) {
  92380. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92381. internalTexture = _this._blurTexture2.getInternalTexture();
  92382. if (internalTexture) {
  92383. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92384. }
  92385. }
  92386. });
  92387. // Prevent autoClear.
  92388. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92389. };
  92390. /**
  92391. * Checks for the readiness of the element composing the layer.
  92392. * @param subMesh the mesh to check for
  92393. * @param useInstances specify wether or not to use instances to render the mesh
  92394. * @param emissiveTexture the associated emissive texture used to generate the glow
  92395. * @return true if ready otherwise, false
  92396. */
  92397. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92398. var material = subMesh.getMaterial();
  92399. var mesh = subMesh.getRenderingMesh();
  92400. if (!material || !mesh) {
  92401. return false;
  92402. }
  92403. var emissiveTexture = material.emissiveTexture;
  92404. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92405. };
  92406. /**
  92407. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92408. */
  92409. GlowLayer.prototype.needStencil = function () {
  92410. return false;
  92411. };
  92412. /**
  92413. * Implementation specific of rendering the generating effect on the main canvas.
  92414. * @param effect The effect used to render through
  92415. */
  92416. GlowLayer.prototype._internalRender = function (effect) {
  92417. // Texture
  92418. effect.setTexture("textureSampler", this._blurTexture1);
  92419. effect.setTexture("textureSampler2", this._blurTexture2);
  92420. effect.setFloat("offset", this._intensity);
  92421. // Cache
  92422. var engine = this._engine;
  92423. var previousStencilBuffer = engine.getStencilBuffer();
  92424. // Draw order
  92425. engine.setStencilBuffer(false);
  92426. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92427. // Draw order
  92428. engine.setStencilBuffer(previousStencilBuffer);
  92429. };
  92430. /**
  92431. * Sets the required values for both the emissive texture and and the main color.
  92432. */
  92433. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92434. var textureLevel = 1.0;
  92435. if (this.customEmissiveTextureSelector) {
  92436. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92437. }
  92438. else {
  92439. if (material) {
  92440. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92441. if (this._emissiveTextureAndColor.texture) {
  92442. textureLevel = this._emissiveTextureAndColor.texture.level;
  92443. }
  92444. }
  92445. else {
  92446. this._emissiveTextureAndColor.texture = null;
  92447. }
  92448. }
  92449. if (this.customEmissiveColorSelector) {
  92450. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92451. }
  92452. else {
  92453. if (material.emissiveColor) {
  92454. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92455. }
  92456. else {
  92457. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92458. }
  92459. }
  92460. };
  92461. /**
  92462. * Returns true if the mesh should render, otherwise false.
  92463. * @param mesh The mesh to render
  92464. * @returns true if it should render otherwise false
  92465. */
  92466. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92467. return this.hasMesh(mesh);
  92468. };
  92469. /**
  92470. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92471. * @param mesh The mesh to exclude from the glow layer
  92472. */
  92473. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92474. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92475. this._excludedMeshes.push(mesh.uniqueId);
  92476. }
  92477. };
  92478. /**
  92479. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92480. * @param mesh The mesh to remove
  92481. */
  92482. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92483. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92484. if (index !== -1) {
  92485. this._excludedMeshes.splice(index, 1);
  92486. }
  92487. };
  92488. /**
  92489. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92490. * @param mesh The mesh to include in the glow layer
  92491. */
  92492. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92493. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92494. this._includedOnlyMeshes.push(mesh.uniqueId);
  92495. }
  92496. };
  92497. /**
  92498. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92499. * @param mesh The mesh to remove
  92500. */
  92501. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92502. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92503. if (index !== -1) {
  92504. this._includedOnlyMeshes.splice(index, 1);
  92505. }
  92506. };
  92507. /**
  92508. * Determine if a given mesh will be used in the glow layer
  92509. * @param mesh The mesh to test
  92510. * @returns true if the mesh will be highlighted by the current glow layer
  92511. */
  92512. GlowLayer.prototype.hasMesh = function (mesh) {
  92513. // Included Mesh
  92514. if (this._includedOnlyMeshes.length) {
  92515. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92516. }
  92517. ;
  92518. // Excluded Mesh
  92519. if (this._excludedMeshes.length) {
  92520. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92521. }
  92522. ;
  92523. return true;
  92524. };
  92525. /**
  92526. * Free any resources and references associated to a mesh.
  92527. * Internal use
  92528. * @param mesh The mesh to free.
  92529. */
  92530. GlowLayer.prototype._disposeMesh = function (mesh) {
  92531. this.removeIncludedOnlyMesh(mesh);
  92532. this.removeExcludedMesh(mesh);
  92533. };
  92534. /**
  92535. * Gets the class name of the effect layer
  92536. * @returns the string with the class name of the effect layer
  92537. */
  92538. GlowLayer.prototype.getClassName = function () {
  92539. return "GlowLayer";
  92540. };
  92541. /**
  92542. * Serializes this glow layer
  92543. * @returns a serialized glow layer object
  92544. */
  92545. GlowLayer.prototype.serialize = function () {
  92546. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92547. serializationObject.customType = "BABYLON.GlowLayer";
  92548. var index;
  92549. // Included meshes
  92550. serializationObject.includedMeshes = [];
  92551. if (this._includedOnlyMeshes.length) {
  92552. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92553. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92554. if (mesh) {
  92555. serializationObject.includedMeshes.push(mesh.id);
  92556. }
  92557. }
  92558. }
  92559. // Excluded meshes
  92560. serializationObject.excludedMeshes = [];
  92561. if (this._excludedMeshes.length) {
  92562. for (index = 0; index < this._excludedMeshes.length; index++) {
  92563. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92564. if (mesh) {
  92565. serializationObject.excludedMeshes.push(mesh.id);
  92566. }
  92567. }
  92568. }
  92569. return serializationObject;
  92570. };
  92571. /**
  92572. * Creates a Glow Layer from parsed glow layer data
  92573. * @param parsedGlowLayer defines glow layer data
  92574. * @param scene defines the current scene
  92575. * @param rootUrl defines the root URL containing the glow layer information
  92576. * @returns a parsed Glow Layer
  92577. */
  92578. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92579. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92580. var index;
  92581. // Excluded meshes
  92582. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92583. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92584. if (mesh) {
  92585. gl.addExcludedMesh(mesh);
  92586. }
  92587. }
  92588. // Included meshes
  92589. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92590. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92591. if (mesh) {
  92592. gl.addIncludedOnlyMesh(mesh);
  92593. }
  92594. }
  92595. return gl;
  92596. };
  92597. /**
  92598. * Effect Name of the layer.
  92599. */
  92600. GlowLayer.EffectName = "GlowLayer";
  92601. /**
  92602. * The default blur kernel size used for the glow.
  92603. */
  92604. GlowLayer.DefaultBlurKernelSize = 32;
  92605. /**
  92606. * The default texture size ratio used for the glow.
  92607. */
  92608. GlowLayer.DefaultTextureRatio = 0.5;
  92609. __decorate([
  92610. BABYLON.serialize()
  92611. ], GlowLayer.prototype, "blurKernelSize", null);
  92612. __decorate([
  92613. BABYLON.serialize()
  92614. ], GlowLayer.prototype, "intensity", null);
  92615. __decorate([
  92616. BABYLON.serialize("options")
  92617. ], GlowLayer.prototype, "_options", void 0);
  92618. return GlowLayer;
  92619. }(BABYLON.EffectLayer));
  92620. BABYLON.GlowLayer = GlowLayer;
  92621. })(BABYLON || (BABYLON = {}));
  92622. //# sourceMappingURL=babylon.glowLayer.js.map
  92623. var BABYLON;
  92624. (function (BABYLON) {
  92625. /**
  92626. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92627. */
  92628. var AssetTaskState;
  92629. (function (AssetTaskState) {
  92630. /**
  92631. * Initialization
  92632. */
  92633. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92634. /**
  92635. * Running
  92636. */
  92637. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92638. /**
  92639. * Done
  92640. */
  92641. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92642. /**
  92643. * Error
  92644. */
  92645. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92646. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92647. /**
  92648. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92649. */
  92650. var AbstractAssetTask = /** @class */ (function () {
  92651. /**
  92652. * Creates a new {BABYLON.AssetsManager}
  92653. * @param name defines the name of the task
  92654. */
  92655. function AbstractAssetTask(
  92656. /**
  92657. * Task name
  92658. */ name) {
  92659. this.name = name;
  92660. this._isCompleted = false;
  92661. this._taskState = AssetTaskState.INIT;
  92662. }
  92663. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92664. /**
  92665. * Get if the task is completed
  92666. */
  92667. get: function () {
  92668. return this._isCompleted;
  92669. },
  92670. enumerable: true,
  92671. configurable: true
  92672. });
  92673. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92674. /**
  92675. * Gets the current state of the task
  92676. */
  92677. get: function () {
  92678. return this._taskState;
  92679. },
  92680. enumerable: true,
  92681. configurable: true
  92682. });
  92683. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92684. /**
  92685. * Gets the current error object (if task is in error)
  92686. */
  92687. get: function () {
  92688. return this._errorObject;
  92689. },
  92690. enumerable: true,
  92691. configurable: true
  92692. });
  92693. /**
  92694. * Internal only
  92695. * @hidden
  92696. */
  92697. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92698. if (this._errorObject) {
  92699. return;
  92700. }
  92701. this._errorObject = {
  92702. message: message,
  92703. exception: exception
  92704. };
  92705. };
  92706. /**
  92707. * Execute the current task
  92708. * @param scene defines the scene where you want your assets to be loaded
  92709. * @param onSuccess is a callback called when the task is successfully executed
  92710. * @param onError is a callback called if an error occurs
  92711. */
  92712. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92713. var _this = this;
  92714. this._taskState = AssetTaskState.RUNNING;
  92715. this.runTask(scene, function () {
  92716. _this.onDoneCallback(onSuccess, onError);
  92717. }, function (msg, exception) {
  92718. _this.onErrorCallback(onError, msg, exception);
  92719. });
  92720. };
  92721. /**
  92722. * Execute the current task
  92723. * @param scene defines the scene where you want your assets to be loaded
  92724. * @param onSuccess is a callback called when the task is successfully executed
  92725. * @param onError is a callback called if an error occurs
  92726. */
  92727. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92728. throw new Error("runTask is not implemented");
  92729. };
  92730. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92731. this._taskState = AssetTaskState.ERROR;
  92732. this._errorObject = {
  92733. message: message,
  92734. exception: exception
  92735. };
  92736. if (this.onError) {
  92737. this.onError(this, message, exception);
  92738. }
  92739. onError();
  92740. };
  92741. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92742. try {
  92743. this._taskState = AssetTaskState.DONE;
  92744. this._isCompleted = true;
  92745. if (this.onSuccess) {
  92746. this.onSuccess(this);
  92747. }
  92748. onSuccess();
  92749. }
  92750. catch (e) {
  92751. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92752. }
  92753. };
  92754. return AbstractAssetTask;
  92755. }());
  92756. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92757. /**
  92758. * Class used to share progress information about assets loading
  92759. */
  92760. var AssetsProgressEvent = /** @class */ (function () {
  92761. /**
  92762. * Creates a {BABYLON.AssetsProgressEvent}
  92763. * @param remainingCount defines the number of remaining tasks to process
  92764. * @param totalCount defines the total number of tasks
  92765. * @param task defines the task that was just processed
  92766. */
  92767. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92768. this.remainingCount = remainingCount;
  92769. this.totalCount = totalCount;
  92770. this.task = task;
  92771. }
  92772. return AssetsProgressEvent;
  92773. }());
  92774. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92775. /**
  92776. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92777. */
  92778. var MeshAssetTask = /** @class */ (function (_super) {
  92779. __extends(MeshAssetTask, _super);
  92780. /**
  92781. * Creates a new {BABYLON.MeshAssetTask}
  92782. * @param name defines the name of the task
  92783. * @param meshesNames defines the list of mesh's names you want to load
  92784. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92785. * @param sceneFilename defines the filename of the scene to load from
  92786. */
  92787. function MeshAssetTask(
  92788. /**
  92789. * Defines the name of the task
  92790. */
  92791. name,
  92792. /**
  92793. * Defines the list of mesh's names you want to load
  92794. */
  92795. meshesNames,
  92796. /**
  92797. * Defines the root url to use as a base to load your meshes and associated resources
  92798. */
  92799. rootUrl,
  92800. /**
  92801. * Defines the filename of the scene to load from
  92802. */
  92803. sceneFilename) {
  92804. var _this = _super.call(this, name) || this;
  92805. _this.name = name;
  92806. _this.meshesNames = meshesNames;
  92807. _this.rootUrl = rootUrl;
  92808. _this.sceneFilename = sceneFilename;
  92809. return _this;
  92810. }
  92811. /**
  92812. * Execute the current task
  92813. * @param scene defines the scene where you want your assets to be loaded
  92814. * @param onSuccess is a callback called when the task is successfully executed
  92815. * @param onError is a callback called if an error occurs
  92816. */
  92817. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92818. var _this = this;
  92819. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92820. _this.loadedMeshes = meshes;
  92821. _this.loadedParticleSystems = particleSystems;
  92822. _this.loadedSkeletons = skeletons;
  92823. onSuccess();
  92824. }, null, function (scene, message, exception) {
  92825. onError(message, exception);
  92826. });
  92827. };
  92828. return MeshAssetTask;
  92829. }(AbstractAssetTask));
  92830. BABYLON.MeshAssetTask = MeshAssetTask;
  92831. /**
  92832. * Define a task used by {BABYLON.AssetsManager} to load text content
  92833. */
  92834. var TextFileAssetTask = /** @class */ (function (_super) {
  92835. __extends(TextFileAssetTask, _super);
  92836. /**
  92837. * Creates a new TextFileAssetTask object
  92838. * @param name defines the name of the task
  92839. * @param url defines the location of the file to load
  92840. */
  92841. function TextFileAssetTask(
  92842. /**
  92843. * Defines the name of the task
  92844. */
  92845. name,
  92846. /**
  92847. * Defines the location of the file to load
  92848. */
  92849. url) {
  92850. var _this = _super.call(this, name) || this;
  92851. _this.name = name;
  92852. _this.url = url;
  92853. return _this;
  92854. }
  92855. /**
  92856. * Execute the current task
  92857. * @param scene defines the scene where you want your assets to be loaded
  92858. * @param onSuccess is a callback called when the task is successfully executed
  92859. * @param onError is a callback called if an error occurs
  92860. */
  92861. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92862. var _this = this;
  92863. scene._loadFile(this.url, function (data) {
  92864. _this.text = data;
  92865. onSuccess();
  92866. }, undefined, false, false, function (request, exception) {
  92867. if (request) {
  92868. onError(request.status + " " + request.statusText, exception);
  92869. }
  92870. });
  92871. };
  92872. return TextFileAssetTask;
  92873. }(AbstractAssetTask));
  92874. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92875. /**
  92876. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92877. */
  92878. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92879. __extends(BinaryFileAssetTask, _super);
  92880. /**
  92881. * Creates a new BinaryFileAssetTask object
  92882. * @param name defines the name of the new task
  92883. * @param url defines the location of the file to load
  92884. */
  92885. function BinaryFileAssetTask(
  92886. /**
  92887. * Defines the name of the task
  92888. */
  92889. name,
  92890. /**
  92891. * Defines the location of the file to load
  92892. */
  92893. url) {
  92894. var _this = _super.call(this, name) || this;
  92895. _this.name = name;
  92896. _this.url = url;
  92897. return _this;
  92898. }
  92899. /**
  92900. * Execute the current task
  92901. * @param scene defines the scene where you want your assets to be loaded
  92902. * @param onSuccess is a callback called when the task is successfully executed
  92903. * @param onError is a callback called if an error occurs
  92904. */
  92905. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92906. var _this = this;
  92907. scene._loadFile(this.url, function (data) {
  92908. _this.data = data;
  92909. onSuccess();
  92910. }, undefined, true, true, function (request, exception) {
  92911. if (request) {
  92912. onError(request.status + " " + request.statusText, exception);
  92913. }
  92914. });
  92915. };
  92916. return BinaryFileAssetTask;
  92917. }(AbstractAssetTask));
  92918. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92919. /**
  92920. * Define a task used by {BABYLON.AssetsManager} to load images
  92921. */
  92922. var ImageAssetTask = /** @class */ (function (_super) {
  92923. __extends(ImageAssetTask, _super);
  92924. /**
  92925. * Creates a new ImageAssetTask
  92926. * @param name defines the name of the task
  92927. * @param url defines the location of the image to load
  92928. */
  92929. function ImageAssetTask(
  92930. /**
  92931. * Defines the name of the task
  92932. */
  92933. name,
  92934. /**
  92935. * Defines the location of the image to load
  92936. */
  92937. url) {
  92938. var _this = _super.call(this, name) || this;
  92939. _this.name = name;
  92940. _this.url = url;
  92941. return _this;
  92942. }
  92943. /**
  92944. * Execute the current task
  92945. * @param scene defines the scene where you want your assets to be loaded
  92946. * @param onSuccess is a callback called when the task is successfully executed
  92947. * @param onError is a callback called if an error occurs
  92948. */
  92949. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92950. var _this = this;
  92951. var img = new Image();
  92952. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92953. img.onload = function () {
  92954. _this.image = img;
  92955. onSuccess();
  92956. };
  92957. img.onerror = function (err) {
  92958. onError("Error loading image", err);
  92959. };
  92960. img.src = this.url;
  92961. };
  92962. return ImageAssetTask;
  92963. }(AbstractAssetTask));
  92964. BABYLON.ImageAssetTask = ImageAssetTask;
  92965. /**
  92966. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92967. */
  92968. var TextureAssetTask = /** @class */ (function (_super) {
  92969. __extends(TextureAssetTask, _super);
  92970. /**
  92971. * Creates a new TextureAssetTask object
  92972. * @param name defines the name of the task
  92973. * @param url defines the location of the file to load
  92974. * @param noMipmap defines if mipmap should not be generated (default is false)
  92975. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92976. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92977. */
  92978. function TextureAssetTask(
  92979. /**
  92980. * Defines the name of the task
  92981. */
  92982. name,
  92983. /**
  92984. * Defines the location of the file to load
  92985. */
  92986. url,
  92987. /**
  92988. * Defines if mipmap should not be generated (default is false)
  92989. */
  92990. noMipmap,
  92991. /**
  92992. * Defines if texture must be inverted on Y axis (default is false)
  92993. */
  92994. invertY,
  92995. /**
  92996. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92997. */
  92998. samplingMode) {
  92999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93000. var _this = _super.call(this, name) || this;
  93001. _this.name = name;
  93002. _this.url = url;
  93003. _this.noMipmap = noMipmap;
  93004. _this.invertY = invertY;
  93005. _this.samplingMode = samplingMode;
  93006. return _this;
  93007. }
  93008. /**
  93009. * Execute the current task
  93010. * @param scene defines the scene where you want your assets to be loaded
  93011. * @param onSuccess is a callback called when the task is successfully executed
  93012. * @param onError is a callback called if an error occurs
  93013. */
  93014. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93015. var onload = function () {
  93016. onSuccess();
  93017. };
  93018. var onerror = function (message, exception) {
  93019. onError(message, exception);
  93020. };
  93021. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93022. };
  93023. return TextureAssetTask;
  93024. }(AbstractAssetTask));
  93025. BABYLON.TextureAssetTask = TextureAssetTask;
  93026. /**
  93027. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93028. */
  93029. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93030. __extends(CubeTextureAssetTask, _super);
  93031. /**
  93032. * Creates a new CubeTextureAssetTask
  93033. * @param name defines the name of the task
  93034. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93035. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93036. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93037. * @param files defines the explicit list of files (undefined by default)
  93038. */
  93039. function CubeTextureAssetTask(
  93040. /**
  93041. * Defines the name of the task
  93042. */
  93043. name,
  93044. /**
  93045. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93046. */
  93047. url,
  93048. /**
  93049. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93050. */
  93051. extensions,
  93052. /**
  93053. * Defines if mipmaps should not be generated (default is false)
  93054. */
  93055. noMipmap,
  93056. /**
  93057. * Defines the explicit list of files (undefined by default)
  93058. */
  93059. files) {
  93060. var _this = _super.call(this, name) || this;
  93061. _this.name = name;
  93062. _this.url = url;
  93063. _this.extensions = extensions;
  93064. _this.noMipmap = noMipmap;
  93065. _this.files = files;
  93066. return _this;
  93067. }
  93068. /**
  93069. * Execute the current task
  93070. * @param scene defines the scene where you want your assets to be loaded
  93071. * @param onSuccess is a callback called when the task is successfully executed
  93072. * @param onError is a callback called if an error occurs
  93073. */
  93074. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93075. var onload = function () {
  93076. onSuccess();
  93077. };
  93078. var onerror = function (message, exception) {
  93079. onError(message, exception);
  93080. };
  93081. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93082. };
  93083. return CubeTextureAssetTask;
  93084. }(AbstractAssetTask));
  93085. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93086. /**
  93087. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93088. */
  93089. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93090. __extends(HDRCubeTextureAssetTask, _super);
  93091. /**
  93092. * Creates a new HDRCubeTextureAssetTask object
  93093. * @param name defines the name of the task
  93094. * @param url defines the location of the file to load
  93095. * @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.
  93096. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93097. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93098. * @param useInGammaSpace 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)
  93099. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  93100. */
  93101. function HDRCubeTextureAssetTask(
  93102. /**
  93103. * Defines the name of the task
  93104. */
  93105. name,
  93106. /**
  93107. * Defines the location of the file to load
  93108. */
  93109. url,
  93110. /**
  93111. * 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.
  93112. */
  93113. size,
  93114. /**
  93115. * Defines if mipmaps should not be generated (default is false)
  93116. */
  93117. noMipmap,
  93118. /**
  93119. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93120. */
  93121. generateHarmonics,
  93122. /**
  93123. * 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)
  93124. */
  93125. useInGammaSpace,
  93126. /**
  93127. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  93128. */
  93129. usePMREMGenerator) {
  93130. if (noMipmap === void 0) { noMipmap = false; }
  93131. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93132. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  93133. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  93134. var _this = _super.call(this, name) || this;
  93135. _this.name = name;
  93136. _this.url = url;
  93137. _this.size = size;
  93138. _this.noMipmap = noMipmap;
  93139. _this.generateHarmonics = generateHarmonics;
  93140. _this.useInGammaSpace = useInGammaSpace;
  93141. _this.usePMREMGenerator = usePMREMGenerator;
  93142. return _this;
  93143. }
  93144. /**
  93145. * Execute the current task
  93146. * @param scene defines the scene where you want your assets to be loaded
  93147. * @param onSuccess is a callback called when the task is successfully executed
  93148. * @param onError is a callback called if an error occurs
  93149. */
  93150. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93151. var onload = function () {
  93152. onSuccess();
  93153. };
  93154. var onerror = function (message, exception) {
  93155. onError(message, exception);
  93156. };
  93157. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  93158. };
  93159. return HDRCubeTextureAssetTask;
  93160. }(AbstractAssetTask));
  93161. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93162. /**
  93163. * This class can be used to easily import assets into a scene
  93164. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93165. */
  93166. var AssetsManager = /** @class */ (function () {
  93167. /**
  93168. * Creates a new AssetsManager
  93169. * @param scene defines the scene to work on
  93170. */
  93171. function AssetsManager(scene) {
  93172. this._isLoading = false;
  93173. this._tasks = new Array();
  93174. this._waitingTasksCount = 0;
  93175. this._totalTasksCount = 0;
  93176. /**
  93177. * Observable called when all tasks are processed
  93178. */
  93179. this.onTaskSuccessObservable = new BABYLON.Observable();
  93180. /**
  93181. * Observable called when a task had an error
  93182. */
  93183. this.onTaskErrorObservable = new BABYLON.Observable();
  93184. /**
  93185. * Observable called when a task is successful
  93186. */
  93187. this.onTasksDoneObservable = new BABYLON.Observable();
  93188. /**
  93189. * Observable called when a task is done (whatever the result is)
  93190. */
  93191. this.onProgressObservable = new BABYLON.Observable();
  93192. /**
  93193. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93194. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93195. */
  93196. this.useDefaultLoadingScreen = true;
  93197. this._scene = scene;
  93198. }
  93199. /**
  93200. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93201. * @param taskName defines the name of the new task
  93202. * @param meshesNames defines the name of meshes to load
  93203. * @param rootUrl defines the root url to use to locate files
  93204. * @param sceneFilename defines the filename of the scene file
  93205. * @returns a new {BABYLON.MeshAssetTask} object
  93206. */
  93207. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93208. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93209. this._tasks.push(task);
  93210. return task;
  93211. };
  93212. /**
  93213. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93214. * @param taskName defines the name of the new task
  93215. * @param url defines the url of the file to load
  93216. * @returns a new {BABYLON.TextFileAssetTask} object
  93217. */
  93218. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93219. var task = new TextFileAssetTask(taskName, url);
  93220. this._tasks.push(task);
  93221. return task;
  93222. };
  93223. /**
  93224. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93225. * @param taskName defines the name of the new task
  93226. * @param url defines the url of the file to load
  93227. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93228. */
  93229. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93230. var task = new BinaryFileAssetTask(taskName, url);
  93231. this._tasks.push(task);
  93232. return task;
  93233. };
  93234. /**
  93235. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93236. * @param taskName defines the name of the new task
  93237. * @param url defines the url of the file to load
  93238. * @returns a new {BABYLON.ImageAssetTask} object
  93239. */
  93240. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93241. var task = new ImageAssetTask(taskName, url);
  93242. this._tasks.push(task);
  93243. return task;
  93244. };
  93245. /**
  93246. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93247. * @param taskName defines the name of the new task
  93248. * @param url defines the url of the file to load
  93249. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93250. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93251. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93252. * @returns a new {BABYLON.TextureAssetTask} object
  93253. */
  93254. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93256. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93257. this._tasks.push(task);
  93258. return task;
  93259. };
  93260. /**
  93261. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93262. * @param taskName defines the name of the new task
  93263. * @param url defines the url of the file to load
  93264. * @param extensions defines the extension to use to load the cube map (can be null)
  93265. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93266. * @param files defines the list of files to load (can be null)
  93267. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93268. */
  93269. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93270. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93271. this._tasks.push(task);
  93272. return task;
  93273. };
  93274. /**
  93275. *
  93276. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93277. * @param taskName defines the name of the new task
  93278. * @param url defines the url of the file to load
  93279. * @param size defines the size you want for the cubemap (can be null)
  93280. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93281. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93282. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  93283. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  93284. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93285. */
  93286. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  93287. if (noMipmap === void 0) { noMipmap = false; }
  93288. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93289. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  93290. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  93291. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  93292. this._tasks.push(task);
  93293. return task;
  93294. };
  93295. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93296. var _this = this;
  93297. this._waitingTasksCount--;
  93298. try {
  93299. if (task.taskState === AssetTaskState.DONE) {
  93300. // Let's remove successfull tasks
  93301. BABYLON.Tools.SetImmediate(function () {
  93302. var index = _this._tasks.indexOf(task);
  93303. if (index > -1) {
  93304. _this._tasks.splice(index, 1);
  93305. }
  93306. });
  93307. }
  93308. if (this.onProgress) {
  93309. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93310. }
  93311. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93312. }
  93313. catch (e) {
  93314. BABYLON.Tools.Error("Error running progress callbacks.");
  93315. console.log(e);
  93316. }
  93317. if (this._waitingTasksCount === 0) {
  93318. try {
  93319. if (this.onFinish) {
  93320. this.onFinish(this._tasks);
  93321. }
  93322. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93323. }
  93324. catch (e) {
  93325. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93326. console.log(e);
  93327. }
  93328. this._isLoading = false;
  93329. this._scene.getEngine().hideLoadingUI();
  93330. }
  93331. };
  93332. AssetsManager.prototype._runTask = function (task) {
  93333. var _this = this;
  93334. var done = function () {
  93335. try {
  93336. if (_this.onTaskSuccess) {
  93337. _this.onTaskSuccess(task);
  93338. }
  93339. _this.onTaskSuccessObservable.notifyObservers(task);
  93340. _this._decreaseWaitingTasksCount(task);
  93341. }
  93342. catch (e) {
  93343. error("Error executing task success callbacks", e);
  93344. }
  93345. };
  93346. var error = function (message, exception) {
  93347. task._setErrorObject(message, exception);
  93348. if (_this.onTaskError) {
  93349. _this.onTaskError(task);
  93350. }
  93351. _this.onTaskErrorObservable.notifyObservers(task);
  93352. _this._decreaseWaitingTasksCount(task);
  93353. };
  93354. task.run(this._scene, done, error);
  93355. };
  93356. /**
  93357. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93358. * @return the current instance of the {BABYLON.AssetsManager}
  93359. */
  93360. AssetsManager.prototype.reset = function () {
  93361. this._isLoading = false;
  93362. this._tasks = new Array();
  93363. return this;
  93364. };
  93365. /**
  93366. * Start the loading process
  93367. * @return the current instance of the {BABYLON.AssetsManager}
  93368. */
  93369. AssetsManager.prototype.load = function () {
  93370. if (this._isLoading) {
  93371. return this;
  93372. }
  93373. this._isLoading = true;
  93374. this._waitingTasksCount = this._tasks.length;
  93375. this._totalTasksCount = this._tasks.length;
  93376. if (this._waitingTasksCount === 0) {
  93377. this._isLoading = false;
  93378. if (this.onFinish) {
  93379. this.onFinish(this._tasks);
  93380. }
  93381. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93382. return this;
  93383. }
  93384. if (this.useDefaultLoadingScreen) {
  93385. this._scene.getEngine().displayLoadingUI();
  93386. }
  93387. for (var index = 0; index < this._tasks.length; index++) {
  93388. var task = this._tasks[index];
  93389. this._runTask(task);
  93390. }
  93391. return this;
  93392. };
  93393. return AssetsManager;
  93394. }());
  93395. BABYLON.AssetsManager = AssetsManager;
  93396. })(BABYLON || (BABYLON = {}));
  93397. //# sourceMappingURL=babylon.assetsManager.js.map
  93398. var BABYLON;
  93399. (function (BABYLON) {
  93400. var serializedGeometries = [];
  93401. var serializeGeometry = function (geometry, serializationGeometries) {
  93402. if (serializedGeometries[geometry.id]) {
  93403. return;
  93404. }
  93405. if (geometry.doNotSerialize) {
  93406. return;
  93407. }
  93408. if (geometry instanceof BABYLON.BoxGeometry) {
  93409. serializationGeometries.boxes.push(geometry.serialize());
  93410. }
  93411. else if (geometry instanceof BABYLON.SphereGeometry) {
  93412. serializationGeometries.spheres.push(geometry.serialize());
  93413. }
  93414. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93415. serializationGeometries.cylinders.push(geometry.serialize());
  93416. }
  93417. else if (geometry instanceof BABYLON.TorusGeometry) {
  93418. serializationGeometries.toruses.push(geometry.serialize());
  93419. }
  93420. else if (geometry instanceof BABYLON.GroundGeometry) {
  93421. serializationGeometries.grounds.push(geometry.serialize());
  93422. }
  93423. else if (geometry instanceof BABYLON.Plane) {
  93424. serializationGeometries.planes.push(geometry.serialize());
  93425. }
  93426. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93427. serializationGeometries.torusKnots.push(geometry.serialize());
  93428. }
  93429. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93430. throw new Error("Unknown primitive type");
  93431. }
  93432. else {
  93433. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93434. }
  93435. serializedGeometries[geometry.id] = true;
  93436. };
  93437. var serializeMesh = function (mesh, serializationScene) {
  93438. var serializationObject = {};
  93439. // Geometry
  93440. var geometry = mesh._geometry;
  93441. if (geometry) {
  93442. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93443. // 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
  93444. serializeGeometry(geometry, serializationScene.geometries);
  93445. }
  93446. }
  93447. // Custom
  93448. if (mesh.serialize) {
  93449. mesh.serialize(serializationObject);
  93450. }
  93451. return serializationObject;
  93452. };
  93453. var finalizeSingleMesh = function (mesh, serializationObject) {
  93454. //only works if the mesh is already loaded
  93455. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93456. //serialize material
  93457. if (mesh.material) {
  93458. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93459. serializationObject.materials = serializationObject.materials || [];
  93460. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93461. serializationObject.materials.push(mesh.material.serialize());
  93462. }
  93463. }
  93464. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93465. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93466. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93467. serializationObject.multiMaterials.push(mesh.material.serialize());
  93468. }
  93469. }
  93470. }
  93471. //serialize geometry
  93472. var geometry = mesh._geometry;
  93473. if (geometry) {
  93474. if (!serializationObject.geometries) {
  93475. serializationObject.geometries = {};
  93476. serializationObject.geometries.boxes = [];
  93477. serializationObject.geometries.spheres = [];
  93478. serializationObject.geometries.cylinders = [];
  93479. serializationObject.geometries.toruses = [];
  93480. serializationObject.geometries.grounds = [];
  93481. serializationObject.geometries.planes = [];
  93482. serializationObject.geometries.torusKnots = [];
  93483. serializationObject.geometries.vertexData = [];
  93484. }
  93485. serializeGeometry(geometry, serializationObject.geometries);
  93486. }
  93487. // Skeletons
  93488. if (mesh.skeleton) {
  93489. serializationObject.skeletons = serializationObject.skeletons || [];
  93490. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93491. }
  93492. //serialize the actual mesh
  93493. serializationObject.meshes = serializationObject.meshes || [];
  93494. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93495. }
  93496. };
  93497. var SceneSerializer = /** @class */ (function () {
  93498. function SceneSerializer() {
  93499. }
  93500. SceneSerializer.ClearCache = function () {
  93501. serializedGeometries = [];
  93502. };
  93503. SceneSerializer.Serialize = function (scene) {
  93504. var serializationObject = {};
  93505. SceneSerializer.ClearCache();
  93506. // Scene
  93507. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93508. serializationObject.autoClear = scene.autoClear;
  93509. serializationObject.clearColor = scene.clearColor.asArray();
  93510. serializationObject.ambientColor = scene.ambientColor.asArray();
  93511. serializationObject.gravity = scene.gravity.asArray();
  93512. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93513. serializationObject.workerCollisions = scene.workerCollisions;
  93514. // Fog
  93515. if (scene.fogMode && scene.fogMode !== 0) {
  93516. serializationObject.fogMode = scene.fogMode;
  93517. serializationObject.fogColor = scene.fogColor.asArray();
  93518. serializationObject.fogStart = scene.fogStart;
  93519. serializationObject.fogEnd = scene.fogEnd;
  93520. serializationObject.fogDensity = scene.fogDensity;
  93521. }
  93522. //Physics
  93523. if (scene.isPhysicsEnabled()) {
  93524. var physicEngine = scene.getPhysicsEngine();
  93525. if (physicEngine) {
  93526. serializationObject.physicsEnabled = true;
  93527. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93528. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93529. }
  93530. }
  93531. // Metadata
  93532. if (scene.metadata) {
  93533. serializationObject.metadata = scene.metadata;
  93534. }
  93535. // Morph targets
  93536. serializationObject.morphTargetManagers = [];
  93537. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93538. var abstractMesh = _a[_i];
  93539. var manager = abstractMesh.morphTargetManager;
  93540. if (manager) {
  93541. serializationObject.morphTargetManagers.push(manager.serialize());
  93542. }
  93543. }
  93544. // Lights
  93545. serializationObject.lights = [];
  93546. var index;
  93547. var light;
  93548. for (index = 0; index < scene.lights.length; index++) {
  93549. light = scene.lights[index];
  93550. if (!light.doNotSerialize) {
  93551. serializationObject.lights.push(light.serialize());
  93552. }
  93553. }
  93554. // Cameras
  93555. serializationObject.cameras = [];
  93556. for (index = 0; index < scene.cameras.length; index++) {
  93557. var camera = scene.cameras[index];
  93558. if (!camera.doNotSerialize) {
  93559. serializationObject.cameras.push(camera.serialize());
  93560. }
  93561. }
  93562. if (scene.activeCamera) {
  93563. serializationObject.activeCameraID = scene.activeCamera.id;
  93564. }
  93565. // Animations
  93566. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93567. // Materials
  93568. serializationObject.materials = [];
  93569. serializationObject.multiMaterials = [];
  93570. var material;
  93571. for (index = 0; index < scene.materials.length; index++) {
  93572. material = scene.materials[index];
  93573. if (!material.doNotSerialize) {
  93574. serializationObject.materials.push(material.serialize());
  93575. }
  93576. }
  93577. // MultiMaterials
  93578. serializationObject.multiMaterials = [];
  93579. for (index = 0; index < scene.multiMaterials.length; index++) {
  93580. var multiMaterial = scene.multiMaterials[index];
  93581. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93582. }
  93583. // Environment texture
  93584. if (scene.environmentTexture) {
  93585. serializationObject.environmentTexture = scene.environmentTexture.name;
  93586. }
  93587. // Skeletons
  93588. serializationObject.skeletons = [];
  93589. for (index = 0; index < scene.skeletons.length; index++) {
  93590. var skeleton = scene.skeletons[index];
  93591. if (!skeleton.doNotSerialize) {
  93592. serializationObject.skeletons.push(skeleton.serialize());
  93593. }
  93594. }
  93595. // Transform nodes
  93596. serializationObject.transformNodes = [];
  93597. for (index = 0; index < scene.transformNodes.length; index++) {
  93598. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93599. }
  93600. // Geometries
  93601. serializationObject.geometries = {};
  93602. serializationObject.geometries.boxes = [];
  93603. serializationObject.geometries.spheres = [];
  93604. serializationObject.geometries.cylinders = [];
  93605. serializationObject.geometries.toruses = [];
  93606. serializationObject.geometries.grounds = [];
  93607. serializationObject.geometries.planes = [];
  93608. serializationObject.geometries.torusKnots = [];
  93609. serializationObject.geometries.vertexData = [];
  93610. serializedGeometries = [];
  93611. var geometries = scene.getGeometries();
  93612. for (index = 0; index < geometries.length; index++) {
  93613. var geometry = geometries[index];
  93614. if (geometry.isReady()) {
  93615. serializeGeometry(geometry, serializationObject.geometries);
  93616. }
  93617. }
  93618. // Meshes
  93619. serializationObject.meshes = [];
  93620. for (index = 0; index < scene.meshes.length; index++) {
  93621. var abstractMesh = scene.meshes[index];
  93622. if (abstractMesh instanceof BABYLON.Mesh) {
  93623. var mesh = abstractMesh;
  93624. if (!mesh.doNotSerialize) {
  93625. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93626. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93627. }
  93628. }
  93629. }
  93630. }
  93631. // Particles Systems
  93632. serializationObject.particleSystems = [];
  93633. for (index = 0; index < scene.particleSystems.length; index++) {
  93634. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93635. }
  93636. // Lens flares
  93637. serializationObject.lensFlareSystems = [];
  93638. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93639. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93640. }
  93641. // Shadows
  93642. serializationObject.shadowGenerators = [];
  93643. for (index = 0; index < scene.lights.length; index++) {
  93644. light = scene.lights[index];
  93645. var shadowGenerator = light.getShadowGenerator();
  93646. if (shadowGenerator) {
  93647. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93648. }
  93649. }
  93650. // Action Manager
  93651. if (scene.actionManager) {
  93652. serializationObject.actions = scene.actionManager.serialize("scene");
  93653. }
  93654. // Audio
  93655. serializationObject.sounds = [];
  93656. for (index = 0; index < scene.soundTracks.length; index++) {
  93657. var soundtrack = scene.soundTracks[index];
  93658. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93659. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93660. }
  93661. }
  93662. // Effect layers
  93663. serializationObject.effectLayers = [];
  93664. for (index = 0; index < scene.effectLayers.length; index++) {
  93665. var layer = scene.effectLayers[index];
  93666. if (layer.serialize) {
  93667. serializationObject.effectLayers.push(layer.serialize());
  93668. }
  93669. }
  93670. return serializationObject;
  93671. };
  93672. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93673. if (withParents === void 0) { withParents = false; }
  93674. if (withChildren === void 0) { withChildren = false; }
  93675. var serializationObject = {};
  93676. SceneSerializer.ClearCache();
  93677. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93678. if (withParents || withChildren) {
  93679. //deliberate for loop! not for each, appended should be processed as well.
  93680. for (var i = 0; i < toSerialize.length; ++i) {
  93681. if (withChildren) {
  93682. toSerialize[i].getDescendants().forEach(function (node) {
  93683. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93684. toSerialize.push(node);
  93685. }
  93686. });
  93687. }
  93688. //make sure the array doesn't contain the object already
  93689. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93690. toSerialize.push(toSerialize[i].parent);
  93691. }
  93692. }
  93693. }
  93694. toSerialize.forEach(function (mesh) {
  93695. finalizeSingleMesh(mesh, serializationObject);
  93696. });
  93697. return serializationObject;
  93698. };
  93699. return SceneSerializer;
  93700. }());
  93701. BABYLON.SceneSerializer = SceneSerializer;
  93702. })(BABYLON || (BABYLON = {}));
  93703. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93704. var BABYLON;
  93705. (function (BABYLON) {
  93706. var ReflectionProbe = /** @class */ (function () {
  93707. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93708. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93709. var _this = this;
  93710. this.name = name;
  93711. this._viewMatrix = BABYLON.Matrix.Identity();
  93712. this._target = BABYLON.Vector3.Zero();
  93713. this._add = BABYLON.Vector3.Zero();
  93714. this._invertYAxis = false;
  93715. this.position = BABYLON.Vector3.Zero();
  93716. this._scene = scene;
  93717. this._scene.reflectionProbes.push(this);
  93718. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93719. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93720. switch (faceIndex) {
  93721. case 0:
  93722. _this._add.copyFromFloats(1, 0, 0);
  93723. break;
  93724. case 1:
  93725. _this._add.copyFromFloats(-1, 0, 0);
  93726. break;
  93727. case 2:
  93728. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93729. break;
  93730. case 3:
  93731. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93732. break;
  93733. case 4:
  93734. _this._add.copyFromFloats(0, 0, 1);
  93735. break;
  93736. case 5:
  93737. _this._add.copyFromFloats(0, 0, -1);
  93738. break;
  93739. }
  93740. if (_this._attachedMesh) {
  93741. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93742. }
  93743. _this.position.addToRef(_this._add, _this._target);
  93744. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93745. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93746. scene._forcedViewPosition = _this.position;
  93747. });
  93748. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93749. scene._forcedViewPosition = null;
  93750. scene.updateTransformMatrix(true);
  93751. });
  93752. if (scene.activeCamera) {
  93753. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93754. }
  93755. }
  93756. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93757. get: function () {
  93758. return this._renderTargetTexture.samples;
  93759. },
  93760. set: function (value) {
  93761. this._renderTargetTexture.samples = value;
  93762. },
  93763. enumerable: true,
  93764. configurable: true
  93765. });
  93766. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93767. get: function () {
  93768. return this._renderTargetTexture.refreshRate;
  93769. },
  93770. set: function (value) {
  93771. this._renderTargetTexture.refreshRate = value;
  93772. },
  93773. enumerable: true,
  93774. configurable: true
  93775. });
  93776. ReflectionProbe.prototype.getScene = function () {
  93777. return this._scene;
  93778. };
  93779. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93780. get: function () {
  93781. return this._renderTargetTexture;
  93782. },
  93783. enumerable: true,
  93784. configurable: true
  93785. });
  93786. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93787. get: function () {
  93788. return this._renderTargetTexture.renderList;
  93789. },
  93790. enumerable: true,
  93791. configurable: true
  93792. });
  93793. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93794. this._attachedMesh = mesh;
  93795. };
  93796. /**
  93797. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93798. *
  93799. * @param renderingGroupId The rendering group id corresponding to its index
  93800. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93801. */
  93802. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93803. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93804. };
  93805. ReflectionProbe.prototype.dispose = function () {
  93806. var index = this._scene.reflectionProbes.indexOf(this);
  93807. if (index !== -1) {
  93808. // Remove from the scene if found
  93809. this._scene.reflectionProbes.splice(index, 1);
  93810. }
  93811. if (this._renderTargetTexture) {
  93812. this._renderTargetTexture.dispose();
  93813. this._renderTargetTexture = null;
  93814. }
  93815. };
  93816. return ReflectionProbe;
  93817. }());
  93818. BABYLON.ReflectionProbe = ReflectionProbe;
  93819. })(BABYLON || (BABYLON = {}));
  93820. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93821. var BABYLON;
  93822. (function (BABYLON) {
  93823. var Layer = /** @class */ (function () {
  93824. function Layer(name, imgUrl, scene, isBackground, color) {
  93825. this.name = name;
  93826. this.scale = new BABYLON.Vector2(1, 1);
  93827. this.offset = new BABYLON.Vector2(0, 0);
  93828. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93829. this.layerMask = 0x0FFFFFFF;
  93830. this._vertexBuffers = {};
  93831. // Events
  93832. /**
  93833. * An event triggered when the layer is disposed.
  93834. */
  93835. this.onDisposeObservable = new BABYLON.Observable();
  93836. /**
  93837. * An event triggered before rendering the scene
  93838. */
  93839. this.onBeforeRenderObservable = new BABYLON.Observable();
  93840. /**
  93841. * An event triggered after rendering the scene
  93842. */
  93843. this.onAfterRenderObservable = new BABYLON.Observable();
  93844. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93845. this.isBackground = isBackground === undefined ? true : isBackground;
  93846. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93847. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93848. this._scene.layers.push(this);
  93849. var engine = this._scene.getEngine();
  93850. // VBO
  93851. var vertices = [];
  93852. vertices.push(1, 1);
  93853. vertices.push(-1, 1);
  93854. vertices.push(-1, -1);
  93855. vertices.push(1, -1);
  93856. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93857. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93858. this._createIndexBuffer();
  93859. // Effects
  93860. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93861. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93862. }
  93863. Object.defineProperty(Layer.prototype, "onDispose", {
  93864. set: function (callback) {
  93865. if (this._onDisposeObserver) {
  93866. this.onDisposeObservable.remove(this._onDisposeObserver);
  93867. }
  93868. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93869. },
  93870. enumerable: true,
  93871. configurable: true
  93872. });
  93873. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93874. set: function (callback) {
  93875. if (this._onBeforeRenderObserver) {
  93876. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93877. }
  93878. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93879. },
  93880. enumerable: true,
  93881. configurable: true
  93882. });
  93883. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93884. set: function (callback) {
  93885. if (this._onAfterRenderObserver) {
  93886. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93887. }
  93888. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93889. },
  93890. enumerable: true,
  93891. configurable: true
  93892. });
  93893. Layer.prototype._createIndexBuffer = function () {
  93894. var engine = this._scene.getEngine();
  93895. // Indices
  93896. var indices = [];
  93897. indices.push(0);
  93898. indices.push(1);
  93899. indices.push(2);
  93900. indices.push(0);
  93901. indices.push(2);
  93902. indices.push(3);
  93903. this._indexBuffer = engine.createIndexBuffer(indices);
  93904. };
  93905. Layer.prototype._rebuild = function () {
  93906. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93907. if (vb) {
  93908. vb._rebuild();
  93909. }
  93910. this._createIndexBuffer();
  93911. };
  93912. Layer.prototype.render = function () {
  93913. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93914. // Check
  93915. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93916. return;
  93917. var engine = this._scene.getEngine();
  93918. this.onBeforeRenderObservable.notifyObservers(this);
  93919. // Render
  93920. engine.enableEffect(currentEffect);
  93921. engine.setState(false);
  93922. // Texture
  93923. currentEffect.setTexture("textureSampler", this.texture);
  93924. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93925. // Color
  93926. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93927. // Scale / offset
  93928. currentEffect.setVector2("offset", this.offset);
  93929. currentEffect.setVector2("scale", this.scale);
  93930. // VBOs
  93931. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93932. // Draw order
  93933. if (!this.alphaTest) {
  93934. engine.setAlphaMode(this.alphaBlendingMode);
  93935. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93936. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93937. }
  93938. else {
  93939. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93940. }
  93941. this.onAfterRenderObservable.notifyObservers(this);
  93942. };
  93943. Layer.prototype.dispose = function () {
  93944. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93945. if (vertexBuffer) {
  93946. vertexBuffer.dispose();
  93947. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93948. }
  93949. if (this._indexBuffer) {
  93950. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93951. this._indexBuffer = null;
  93952. }
  93953. if (this.texture) {
  93954. this.texture.dispose();
  93955. this.texture = null;
  93956. }
  93957. // Remove from scene
  93958. var index = this._scene.layers.indexOf(this);
  93959. this._scene.layers.splice(index, 1);
  93960. // Callback
  93961. this.onDisposeObservable.notifyObservers(this);
  93962. this.onDisposeObservable.clear();
  93963. this.onAfterRenderObservable.clear();
  93964. this.onBeforeRenderObservable.clear();
  93965. };
  93966. return Layer;
  93967. }());
  93968. BABYLON.Layer = Layer;
  93969. })(BABYLON || (BABYLON = {}));
  93970. //# sourceMappingURL=babylon.layer.js.map
  93971. var BABYLON;
  93972. (function (BABYLON) {
  93973. var TextureTools = /** @class */ (function () {
  93974. function TextureTools() {
  93975. }
  93976. /**
  93977. * Uses the GPU to create a copy texture rescaled at a given size
  93978. * @param texture Texture to copy from
  93979. * @param width Desired width
  93980. * @param height Desired height
  93981. * @return Generated texture
  93982. */
  93983. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93984. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93985. var scene = texture.getScene();
  93986. var engine = scene.getEngine();
  93987. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93988. rtt.wrapU = texture.wrapU;
  93989. rtt.wrapV = texture.wrapV;
  93990. rtt.uOffset = texture.uOffset;
  93991. rtt.vOffset = texture.vOffset;
  93992. rtt.uScale = texture.uScale;
  93993. rtt.vScale = texture.vScale;
  93994. rtt.uAng = texture.uAng;
  93995. rtt.vAng = texture.vAng;
  93996. rtt.wAng = texture.wAng;
  93997. rtt.coordinatesIndex = texture.coordinatesIndex;
  93998. rtt.level = texture.level;
  93999. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94000. rtt._texture.isReady = false;
  94001. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94002. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94003. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94004. passPostProcess.getEffect().executeWhenCompiled(function () {
  94005. passPostProcess.onApply = function (effect) {
  94006. effect.setTexture("textureSampler", texture);
  94007. };
  94008. var internalTexture = rtt.getInternalTexture();
  94009. if (internalTexture) {
  94010. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94011. engine.unBindFramebuffer(internalTexture);
  94012. rtt.disposeFramebufferObjects();
  94013. passPostProcess.dispose();
  94014. internalTexture.isReady = true;
  94015. }
  94016. });
  94017. return rtt;
  94018. };
  94019. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94020. if (!scene._environmentBRDFTexture) {
  94021. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94022. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94023. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94024. scene._environmentBRDFTexture = texture;
  94025. }
  94026. return scene._environmentBRDFTexture;
  94027. };
  94028. 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=";
  94029. return TextureTools;
  94030. }());
  94031. BABYLON.TextureTools = TextureTools;
  94032. })(BABYLON || (BABYLON = {}));
  94033. //# sourceMappingURL=babylon.textureTools.js.map
  94034. var BABYLON;
  94035. (function (BABYLON) {
  94036. var FramingBehavior = /** @class */ (function () {
  94037. function FramingBehavior() {
  94038. this._mode = FramingBehavior.FitFrustumSidesMode;
  94039. this._radiusScale = 1.0;
  94040. this._positionScale = 0.5;
  94041. this._defaultElevation = 0.3;
  94042. this._elevationReturnTime = 1500;
  94043. this._elevationReturnWaitTime = 1000;
  94044. this._zoomStopsAnimation = false;
  94045. this._framingTime = 1500;
  94046. this._isPointerDown = false;
  94047. this._lastInteractionTime = -Infinity;
  94048. // Framing control
  94049. this._animatables = new Array();
  94050. this._betaIsAnimating = false;
  94051. }
  94052. Object.defineProperty(FramingBehavior.prototype, "name", {
  94053. get: function () {
  94054. return "Framing";
  94055. },
  94056. enumerable: true,
  94057. configurable: true
  94058. });
  94059. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94060. /**
  94061. * Gets current mode used by the behavior.
  94062. */
  94063. get: function () {
  94064. return this._mode;
  94065. },
  94066. /**
  94067. * Sets the current mode used by the behavior
  94068. */
  94069. set: function (mode) {
  94070. this._mode = mode;
  94071. },
  94072. enumerable: true,
  94073. configurable: true
  94074. });
  94075. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94076. /**
  94077. * Gets the scale applied to the radius
  94078. */
  94079. get: function () {
  94080. return this._radiusScale;
  94081. },
  94082. /**
  94083. * Sets the scale applied to the radius (1 by default)
  94084. */
  94085. set: function (radius) {
  94086. this._radiusScale = radius;
  94087. },
  94088. enumerable: true,
  94089. configurable: true
  94090. });
  94091. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94092. /**
  94093. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94094. */
  94095. get: function () {
  94096. return this._positionScale;
  94097. },
  94098. /**
  94099. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94100. */
  94101. set: function (scale) {
  94102. this._positionScale = scale;
  94103. },
  94104. enumerable: true,
  94105. configurable: true
  94106. });
  94107. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94108. /**
  94109. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94110. * behaviour is triggered, in radians.
  94111. */
  94112. get: function () {
  94113. return this._defaultElevation;
  94114. },
  94115. /**
  94116. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94117. * behaviour is triggered, in radians.
  94118. */
  94119. set: function (elevation) {
  94120. this._defaultElevation = elevation;
  94121. },
  94122. enumerable: true,
  94123. configurable: true
  94124. });
  94125. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94126. /**
  94127. * Gets the time (in milliseconds) taken to return to the default beta position.
  94128. * Negative value indicates camera should not return to default.
  94129. */
  94130. get: function () {
  94131. return this._elevationReturnTime;
  94132. },
  94133. /**
  94134. * Sets the time (in milliseconds) taken to return to the default beta position.
  94135. * Negative value indicates camera should not return to default.
  94136. */
  94137. set: function (speed) {
  94138. this._elevationReturnTime = speed;
  94139. },
  94140. enumerable: true,
  94141. configurable: true
  94142. });
  94143. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94144. /**
  94145. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94146. */
  94147. get: function () {
  94148. return this._elevationReturnWaitTime;
  94149. },
  94150. /**
  94151. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94152. */
  94153. set: function (time) {
  94154. this._elevationReturnWaitTime = time;
  94155. },
  94156. enumerable: true,
  94157. configurable: true
  94158. });
  94159. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94160. /**
  94161. * Gets the flag that indicates if user zooming should stop animation.
  94162. */
  94163. get: function () {
  94164. return this._zoomStopsAnimation;
  94165. },
  94166. /**
  94167. * Sets the flag that indicates if user zooming should stop animation.
  94168. */
  94169. set: function (flag) {
  94170. this._zoomStopsAnimation = flag;
  94171. },
  94172. enumerable: true,
  94173. configurable: true
  94174. });
  94175. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94176. /**
  94177. * Gets the transition time when framing the mesh, in milliseconds
  94178. */
  94179. get: function () {
  94180. return this._framingTime;
  94181. },
  94182. /**
  94183. * Sets the transition time when framing the mesh, in milliseconds
  94184. */
  94185. set: function (time) {
  94186. this._framingTime = time;
  94187. },
  94188. enumerable: true,
  94189. configurable: true
  94190. });
  94191. FramingBehavior.prototype.init = function () {
  94192. // Do notihng
  94193. };
  94194. FramingBehavior.prototype.attach = function (camera) {
  94195. var _this = this;
  94196. this._attachedCamera = camera;
  94197. var scene = this._attachedCamera.getScene();
  94198. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94199. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94200. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94201. _this._isPointerDown = true;
  94202. return;
  94203. }
  94204. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94205. _this._isPointerDown = false;
  94206. }
  94207. });
  94208. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94209. if (mesh) {
  94210. _this.zoomOnMesh(mesh);
  94211. }
  94212. });
  94213. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94214. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94215. _this._applyUserInteraction();
  94216. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94217. // back to the default position after a given timeout
  94218. _this._maintainCameraAboveGround();
  94219. });
  94220. };
  94221. FramingBehavior.prototype.detach = function () {
  94222. if (!this._attachedCamera) {
  94223. return;
  94224. }
  94225. var scene = this._attachedCamera.getScene();
  94226. if (this._onPrePointerObservableObserver) {
  94227. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94228. }
  94229. if (this._onAfterCheckInputsObserver) {
  94230. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94231. }
  94232. if (this._onMeshTargetChangedObserver) {
  94233. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94234. }
  94235. this._attachedCamera = null;
  94236. };
  94237. /**
  94238. * Targets the given mesh and updates zoom level accordingly.
  94239. * @param mesh The mesh to target.
  94240. * @param radius Optional. If a cached radius position already exists, overrides default.
  94241. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94242. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94243. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94244. */
  94245. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94246. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94247. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94248. mesh.computeWorldMatrix(true);
  94249. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94250. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94251. };
  94252. /**
  94253. * Targets the given mesh with its children and updates zoom level accordingly.
  94254. * @param mesh The mesh to target.
  94255. * @param radius Optional. If a cached radius position already exists, overrides default.
  94256. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94257. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94258. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94259. */
  94260. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94261. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94262. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94263. mesh.computeWorldMatrix(true);
  94264. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94265. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94266. };
  94267. /**
  94268. * Targets the given meshes with their children and updates zoom level accordingly.
  94269. * @param meshes The mesh to target.
  94270. * @param radius Optional. If a cached radius position already exists, overrides default.
  94271. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94272. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94273. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94274. */
  94275. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94276. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94277. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94278. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94279. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94280. for (var i = 0; i < meshes.length; i++) {
  94281. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94282. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94283. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94284. }
  94285. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94286. };
  94287. /**
  94288. * Targets the given mesh and updates zoom level accordingly.
  94289. * @param mesh The mesh to target.
  94290. * @param radius Optional. If a cached radius position already exists, overrides default.
  94291. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94292. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94293. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94294. */
  94295. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94296. var _this = this;
  94297. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94298. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94299. var zoomTarget;
  94300. if (!this._attachedCamera) {
  94301. return;
  94302. }
  94303. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94304. var bottom = minimumWorld.y;
  94305. var top = maximumWorld.y;
  94306. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94307. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94308. if (focusOnOriginXZ) {
  94309. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94310. }
  94311. else {
  94312. var centerWorld = minimumWorld.add(radiusWorld);
  94313. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94314. }
  94315. if (!this._vectorTransition) {
  94316. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94317. }
  94318. this._betaIsAnimating = true;
  94319. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94320. if (animatable) {
  94321. this._animatables.push(animatable);
  94322. }
  94323. // sets the radius and lower radius bounds
  94324. // Small delta ensures camera is not always at lower zoom limit.
  94325. var radius = 0;
  94326. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94327. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94328. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94329. radius = position;
  94330. }
  94331. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94332. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94333. if (this._attachedCamera.lowerRadiusLimit === null) {
  94334. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94335. }
  94336. }
  94337. // Set sensibilities
  94338. var extend = maximumWorld.subtract(minimumWorld).length();
  94339. this._attachedCamera.panningSensibility = 5000 / extend;
  94340. this._attachedCamera.wheelPrecision = 100 / radius;
  94341. // transition to new radius
  94342. if (!this._radiusTransition) {
  94343. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94344. }
  94345. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94346. _this.stopAllAnimations();
  94347. if (onAnimationEnd) {
  94348. onAnimationEnd();
  94349. }
  94350. if (_this._attachedCamera) {
  94351. _this._attachedCamera.storeState();
  94352. }
  94353. });
  94354. if (animatable) {
  94355. this._animatables.push(animatable);
  94356. }
  94357. };
  94358. /**
  94359. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94360. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94361. * frustum width.
  94362. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94363. * to fully enclose the mesh in the viewing frustum.
  94364. */
  94365. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94366. var size = maximumWorld.subtract(minimumWorld);
  94367. var boxVectorGlobalDiagonal = size.length();
  94368. var frustumSlope = this._getFrustumSlope();
  94369. // Formula for setting distance
  94370. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94371. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94372. // Horizon distance
  94373. var radius = radiusWithoutFraming * this._radiusScale;
  94374. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94375. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94376. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94377. var camera = this._attachedCamera;
  94378. if (!camera) {
  94379. return 0;
  94380. }
  94381. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94382. // Don't exceed the requested limit
  94383. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94384. }
  94385. // Don't exceed the upper radius limit
  94386. if (camera.upperRadiusLimit) {
  94387. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94388. }
  94389. return distance;
  94390. };
  94391. /**
  94392. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94393. * is automatically returned to its default position (expected to be above ground plane).
  94394. */
  94395. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94396. var _this = this;
  94397. if (this._elevationReturnTime < 0) {
  94398. return;
  94399. }
  94400. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94401. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94402. var limitBeta = Math.PI * 0.5;
  94403. // Bring the camera back up if below the ground plane
  94404. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94405. this._betaIsAnimating = true;
  94406. //Transition to new position
  94407. this.stopAllAnimations();
  94408. if (!this._betaTransition) {
  94409. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94410. }
  94411. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94412. _this._clearAnimationLocks();
  94413. _this.stopAllAnimations();
  94414. });
  94415. if (animatabe) {
  94416. this._animatables.push(animatabe);
  94417. }
  94418. }
  94419. };
  94420. /**
  94421. * Returns the frustum slope based on the canvas ratio and camera FOV
  94422. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94423. */
  94424. FramingBehavior.prototype._getFrustumSlope = function () {
  94425. // Calculate the viewport ratio
  94426. // Aspect Ratio is Height/Width.
  94427. var camera = this._attachedCamera;
  94428. if (!camera) {
  94429. return BABYLON.Vector2.Zero();
  94430. }
  94431. var engine = camera.getScene().getEngine();
  94432. var aspectRatio = engine.getAspectRatio(camera);
  94433. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94434. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94435. var frustumSlopeY = Math.tan(camera.fov / 2);
  94436. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94437. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94438. // along the forward vector.
  94439. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94440. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94441. };
  94442. /**
  94443. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94444. */
  94445. FramingBehavior.prototype._clearAnimationLocks = function () {
  94446. this._betaIsAnimating = false;
  94447. };
  94448. /**
  94449. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94450. */
  94451. FramingBehavior.prototype._applyUserInteraction = function () {
  94452. if (this.isUserIsMoving) {
  94453. this._lastInteractionTime = BABYLON.Tools.Now;
  94454. this.stopAllAnimations();
  94455. this._clearAnimationLocks();
  94456. }
  94457. };
  94458. /**
  94459. * Stops and removes all animations that have been applied to the camera
  94460. */
  94461. FramingBehavior.prototype.stopAllAnimations = function () {
  94462. if (this._attachedCamera) {
  94463. this._attachedCamera.animations = [];
  94464. }
  94465. while (this._animatables.length) {
  94466. if (this._animatables[0]) {
  94467. this._animatables[0].onAnimationEnd = null;
  94468. this._animatables[0].stop();
  94469. }
  94470. this._animatables.shift();
  94471. }
  94472. };
  94473. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94474. /**
  94475. * Gets a value indicating if the user is moving the camera
  94476. */
  94477. get: function () {
  94478. if (!this._attachedCamera) {
  94479. return false;
  94480. }
  94481. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94482. this._attachedCamera.inertialBetaOffset !== 0 ||
  94483. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94484. this._attachedCamera.inertialPanningX !== 0 ||
  94485. this._attachedCamera.inertialPanningY !== 0 ||
  94486. this._isPointerDown;
  94487. },
  94488. enumerable: true,
  94489. configurable: true
  94490. });
  94491. /**
  94492. * The easing function used by animations
  94493. */
  94494. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94495. /**
  94496. * The easing mode used by animations
  94497. */
  94498. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94499. // Statics
  94500. /**
  94501. * The camera can move all the way towards the mesh.
  94502. */
  94503. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94504. /**
  94505. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94506. */
  94507. FramingBehavior.FitFrustumSidesMode = 1;
  94508. return FramingBehavior;
  94509. }());
  94510. BABYLON.FramingBehavior = FramingBehavior;
  94511. })(BABYLON || (BABYLON = {}));
  94512. //# sourceMappingURL=babylon.framingBehavior.js.map
  94513. var BABYLON;
  94514. (function (BABYLON) {
  94515. /**
  94516. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94517. */
  94518. var BouncingBehavior = /** @class */ (function () {
  94519. function BouncingBehavior() {
  94520. /**
  94521. * The duration of the animation, in milliseconds
  94522. */
  94523. this.transitionDuration = 450;
  94524. /**
  94525. * Length of the distance animated by the transition when lower radius is reached
  94526. */
  94527. this.lowerRadiusTransitionRange = 2;
  94528. /**
  94529. * Length of the distance animated by the transition when upper radius is reached
  94530. */
  94531. this.upperRadiusTransitionRange = -2;
  94532. this._autoTransitionRange = false;
  94533. // Animations
  94534. this._radiusIsAnimating = false;
  94535. this._radiusBounceTransition = null;
  94536. this._animatables = new Array();
  94537. }
  94538. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94539. get: function () {
  94540. return "Bouncing";
  94541. },
  94542. enumerable: true,
  94543. configurable: true
  94544. });
  94545. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94546. /**
  94547. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94548. */
  94549. get: function () {
  94550. return this._autoTransitionRange;
  94551. },
  94552. /**
  94553. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94554. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94555. */
  94556. set: function (value) {
  94557. var _this = this;
  94558. if (this._autoTransitionRange === value) {
  94559. return;
  94560. }
  94561. this._autoTransitionRange = value;
  94562. var camera = this._attachedCamera;
  94563. if (!camera) {
  94564. return;
  94565. }
  94566. if (value) {
  94567. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94568. if (!mesh) {
  94569. return;
  94570. }
  94571. mesh.computeWorldMatrix(true);
  94572. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94573. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94574. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94575. });
  94576. }
  94577. else if (this._onMeshTargetChangedObserver) {
  94578. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94579. }
  94580. },
  94581. enumerable: true,
  94582. configurable: true
  94583. });
  94584. BouncingBehavior.prototype.init = function () {
  94585. // Do notihng
  94586. };
  94587. BouncingBehavior.prototype.attach = function (camera) {
  94588. var _this = this;
  94589. this._attachedCamera = camera;
  94590. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94591. if (!_this._attachedCamera) {
  94592. return;
  94593. }
  94594. // Add the bounce animation to the lower radius limit
  94595. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94596. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94597. }
  94598. // Add the bounce animation to the upper radius limit
  94599. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94600. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94601. }
  94602. });
  94603. };
  94604. BouncingBehavior.prototype.detach = function () {
  94605. if (!this._attachedCamera) {
  94606. return;
  94607. }
  94608. if (this._onAfterCheckInputsObserver) {
  94609. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94610. }
  94611. if (this._onMeshTargetChangedObserver) {
  94612. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94613. }
  94614. this._attachedCamera = null;
  94615. };
  94616. /**
  94617. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94618. * @param radiusLimit The limit to check against.
  94619. * @return Bool to indicate if at limit.
  94620. */
  94621. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94622. if (!this._attachedCamera) {
  94623. return false;
  94624. }
  94625. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94626. return true;
  94627. }
  94628. return false;
  94629. };
  94630. /**
  94631. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94632. * @param radiusDelta The delta by which to animate to. Can be negative.
  94633. */
  94634. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94635. var _this = this;
  94636. if (!this._attachedCamera) {
  94637. return;
  94638. }
  94639. if (!this._radiusBounceTransition) {
  94640. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94641. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94642. }
  94643. // Prevent zoom until bounce has completed
  94644. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94645. this._attachedCamera.wheelPrecision = Infinity;
  94646. this._attachedCamera.inertialRadiusOffset = 0;
  94647. // Animate to the radius limit
  94648. this.stopAllAnimations();
  94649. this._radiusIsAnimating = true;
  94650. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94651. if (animatable) {
  94652. this._animatables.push(animatable);
  94653. }
  94654. };
  94655. /**
  94656. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94657. */
  94658. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94659. this._radiusIsAnimating = false;
  94660. if (this._attachedCamera) {
  94661. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94662. }
  94663. };
  94664. /**
  94665. * Stops and removes all animations that have been applied to the camera
  94666. */
  94667. BouncingBehavior.prototype.stopAllAnimations = function () {
  94668. if (this._attachedCamera) {
  94669. this._attachedCamera.animations = [];
  94670. }
  94671. while (this._animatables.length) {
  94672. this._animatables[0].onAnimationEnd = null;
  94673. this._animatables[0].stop();
  94674. this._animatables.shift();
  94675. }
  94676. };
  94677. /**
  94678. * The easing function used by animations
  94679. */
  94680. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94681. /**
  94682. * The easing mode used by animations
  94683. */
  94684. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94685. return BouncingBehavior;
  94686. }());
  94687. BABYLON.BouncingBehavior = BouncingBehavior;
  94688. })(BABYLON || (BABYLON = {}));
  94689. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94690. var BABYLON;
  94691. (function (BABYLON) {
  94692. var AutoRotationBehavior = /** @class */ (function () {
  94693. function AutoRotationBehavior() {
  94694. this._zoomStopsAnimation = false;
  94695. this._idleRotationSpeed = 0.05;
  94696. this._idleRotationWaitTime = 2000;
  94697. this._idleRotationSpinupTime = 2000;
  94698. this._isPointerDown = false;
  94699. this._lastFrameTime = null;
  94700. this._lastInteractionTime = -Infinity;
  94701. this._cameraRotationSpeed = 0;
  94702. this._lastFrameRadius = 0;
  94703. }
  94704. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94705. get: function () {
  94706. return "AutoRotation";
  94707. },
  94708. enumerable: true,
  94709. configurable: true
  94710. });
  94711. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94712. /**
  94713. * Gets the flag that indicates if user zooming should stop animation.
  94714. */
  94715. get: function () {
  94716. return this._zoomStopsAnimation;
  94717. },
  94718. /**
  94719. * Sets the flag that indicates if user zooming should stop animation.
  94720. */
  94721. set: function (flag) {
  94722. this._zoomStopsAnimation = flag;
  94723. },
  94724. enumerable: true,
  94725. configurable: true
  94726. });
  94727. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94728. /**
  94729. * Gets the default speed at which the camera rotates around the model.
  94730. */
  94731. get: function () {
  94732. return this._idleRotationSpeed;
  94733. },
  94734. /**
  94735. * Sets the default speed at which the camera rotates around the model.
  94736. */
  94737. set: function (speed) {
  94738. this._idleRotationSpeed = speed;
  94739. },
  94740. enumerable: true,
  94741. configurable: true
  94742. });
  94743. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94744. /**
  94745. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94746. */
  94747. get: function () {
  94748. return this._idleRotationWaitTime;
  94749. },
  94750. /**
  94751. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94752. */
  94753. set: function (time) {
  94754. this._idleRotationWaitTime = time;
  94755. },
  94756. enumerable: true,
  94757. configurable: true
  94758. });
  94759. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94760. /**
  94761. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94762. */
  94763. get: function () {
  94764. return this._idleRotationSpinupTime;
  94765. },
  94766. /**
  94767. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94768. */
  94769. set: function (time) {
  94770. this._idleRotationSpinupTime = time;
  94771. },
  94772. enumerable: true,
  94773. configurable: true
  94774. });
  94775. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94776. /**
  94777. * Gets a value indicating if the camera is currently rotating because of this behavior
  94778. */
  94779. get: function () {
  94780. return Math.abs(this._cameraRotationSpeed) > 0;
  94781. },
  94782. enumerable: true,
  94783. configurable: true
  94784. });
  94785. AutoRotationBehavior.prototype.init = function () {
  94786. // Do notihng
  94787. };
  94788. AutoRotationBehavior.prototype.attach = function (camera) {
  94789. var _this = this;
  94790. this._attachedCamera = camera;
  94791. var scene = this._attachedCamera.getScene();
  94792. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94793. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94794. _this._isPointerDown = true;
  94795. return;
  94796. }
  94797. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94798. _this._isPointerDown = false;
  94799. }
  94800. });
  94801. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94802. var now = BABYLON.Tools.Now;
  94803. var dt = 0;
  94804. if (_this._lastFrameTime != null) {
  94805. dt = now - _this._lastFrameTime;
  94806. }
  94807. _this._lastFrameTime = now;
  94808. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94809. _this._applyUserInteraction();
  94810. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94811. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94812. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94813. // Step camera rotation by rotation speed
  94814. if (_this._attachedCamera) {
  94815. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94816. }
  94817. });
  94818. };
  94819. AutoRotationBehavior.prototype.detach = function () {
  94820. if (!this._attachedCamera) {
  94821. return;
  94822. }
  94823. var scene = this._attachedCamera.getScene();
  94824. if (this._onPrePointerObservableObserver) {
  94825. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94826. }
  94827. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94828. this._attachedCamera = null;
  94829. };
  94830. /**
  94831. * Returns true if user is scrolling.
  94832. * @return true if user is scrolling.
  94833. */
  94834. AutoRotationBehavior.prototype._userIsZooming = function () {
  94835. if (!this._attachedCamera) {
  94836. return false;
  94837. }
  94838. return this._attachedCamera.inertialRadiusOffset !== 0;
  94839. };
  94840. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94841. if (!this._attachedCamera) {
  94842. return false;
  94843. }
  94844. var zoomHasHitLimit = false;
  94845. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94846. zoomHasHitLimit = true;
  94847. }
  94848. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94849. this._lastFrameRadius = this._attachedCamera.radius;
  94850. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94851. };
  94852. /**
  94853. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94854. */
  94855. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94856. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94857. this._lastInteractionTime = BABYLON.Tools.Now;
  94858. }
  94859. };
  94860. // Tools
  94861. AutoRotationBehavior.prototype._userIsMoving = function () {
  94862. if (!this._attachedCamera) {
  94863. return false;
  94864. }
  94865. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94866. this._attachedCamera.inertialBetaOffset !== 0 ||
  94867. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94868. this._attachedCamera.inertialPanningX !== 0 ||
  94869. this._attachedCamera.inertialPanningY !== 0 ||
  94870. this._isPointerDown;
  94871. };
  94872. return AutoRotationBehavior;
  94873. }());
  94874. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94875. })(BABYLON || (BABYLON = {}));
  94876. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94877. var BABYLON;
  94878. (function (BABYLON) {
  94879. var NullEngineOptions = /** @class */ (function () {
  94880. function NullEngineOptions() {
  94881. this.renderWidth = 512;
  94882. this.renderHeight = 256;
  94883. this.textureSize = 512;
  94884. this.deterministicLockstep = false;
  94885. this.lockstepMaxSteps = 4;
  94886. }
  94887. return NullEngineOptions;
  94888. }());
  94889. BABYLON.NullEngineOptions = NullEngineOptions;
  94890. /**
  94891. * The null engine class provides support for headless version of babylon.js.
  94892. * This can be used in server side scenario or for testing purposes
  94893. */
  94894. var NullEngine = /** @class */ (function (_super) {
  94895. __extends(NullEngine, _super);
  94896. function NullEngine(options) {
  94897. if (options === void 0) { options = new NullEngineOptions(); }
  94898. var _this = _super.call(this, null) || this;
  94899. if (options.deterministicLockstep === undefined) {
  94900. options.deterministicLockstep = false;
  94901. }
  94902. if (options.lockstepMaxSteps === undefined) {
  94903. options.lockstepMaxSteps = 4;
  94904. }
  94905. _this._options = options;
  94906. // Init caps
  94907. // We consider we are on a webgl1 capable device
  94908. _this._caps = new BABYLON.EngineCapabilities();
  94909. _this._caps.maxTexturesImageUnits = 16;
  94910. _this._caps.maxVertexTextureImageUnits = 16;
  94911. _this._caps.maxTextureSize = 512;
  94912. _this._caps.maxCubemapTextureSize = 512;
  94913. _this._caps.maxRenderTextureSize = 512;
  94914. _this._caps.maxVertexAttribs = 16;
  94915. _this._caps.maxVaryingVectors = 16;
  94916. _this._caps.maxFragmentUniformVectors = 16;
  94917. _this._caps.maxVertexUniformVectors = 16;
  94918. // Extensions
  94919. _this._caps.standardDerivatives = false;
  94920. _this._caps.astc = null;
  94921. _this._caps.s3tc = null;
  94922. _this._caps.pvrtc = null;
  94923. _this._caps.etc1 = null;
  94924. _this._caps.etc2 = null;
  94925. _this._caps.textureAnisotropicFilterExtension = null;
  94926. _this._caps.maxAnisotropy = 0;
  94927. _this._caps.uintIndices = false;
  94928. _this._caps.fragmentDepthSupported = false;
  94929. _this._caps.highPrecisionShaderSupported = true;
  94930. _this._caps.colorBufferFloat = false;
  94931. _this._caps.textureFloat = false;
  94932. _this._caps.textureFloatLinearFiltering = false;
  94933. _this._caps.textureFloatRender = false;
  94934. _this._caps.textureHalfFloat = false;
  94935. _this._caps.textureHalfFloatLinearFiltering = false;
  94936. _this._caps.textureHalfFloatRender = false;
  94937. _this._caps.textureLOD = false;
  94938. _this._caps.drawBuffersExtension = false;
  94939. _this._caps.depthTextureExtension = false;
  94940. _this._caps.vertexArrayObject = false;
  94941. _this._caps.instancedArrays = false;
  94942. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94943. // Wrappers
  94944. if (typeof URL === "undefined") {
  94945. URL = {
  94946. createObjectURL: function () { },
  94947. revokeObjectURL: function () { }
  94948. };
  94949. }
  94950. if (typeof Blob === "undefined") {
  94951. Blob = function () { };
  94952. }
  94953. return _this;
  94954. }
  94955. NullEngine.prototype.isDeterministicLockStep = function () {
  94956. return this._options.deterministicLockstep;
  94957. };
  94958. NullEngine.prototype.getLockstepMaxSteps = function () {
  94959. return this._options.lockstepMaxSteps;
  94960. };
  94961. NullEngine.prototype.getHardwareScalingLevel = function () {
  94962. return 1.0;
  94963. };
  94964. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94965. return {
  94966. capacity: 0,
  94967. references: 1,
  94968. is32Bits: false
  94969. };
  94970. };
  94971. NullEngine.prototype.createIndexBuffer = function (indices) {
  94972. return {
  94973. capacity: 0,
  94974. references: 1,
  94975. is32Bits: false
  94976. };
  94977. };
  94978. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94979. if (stencil === void 0) { stencil = false; }
  94980. };
  94981. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94982. if (useScreen === void 0) { useScreen = false; }
  94983. if (!useScreen && this._currentRenderTarget) {
  94984. return this._currentRenderTarget.width;
  94985. }
  94986. return this._options.renderWidth;
  94987. };
  94988. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94989. if (useScreen === void 0) { useScreen = false; }
  94990. if (!useScreen && this._currentRenderTarget) {
  94991. return this._currentRenderTarget.height;
  94992. }
  94993. return this._options.renderHeight;
  94994. };
  94995. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94996. this._cachedViewport = viewport;
  94997. };
  94998. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94999. return {
  95000. transformFeedback: null,
  95001. __SPECTOR_rebuildProgram: null
  95002. };
  95003. };
  95004. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95005. return [];
  95006. };
  95007. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95008. return [];
  95009. };
  95010. NullEngine.prototype.bindSamplers = function (effect) {
  95011. this._currentEffect = null;
  95012. };
  95013. NullEngine.prototype.enableEffect = function (effect) {
  95014. this._currentEffect = effect;
  95015. if (effect.onBind) {
  95016. effect.onBind(effect);
  95017. }
  95018. effect.onBindObservable.notifyObservers(effect);
  95019. };
  95020. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95021. if (zOffset === void 0) { zOffset = 0; }
  95022. if (reverseSide === void 0) { reverseSide = false; }
  95023. };
  95024. NullEngine.prototype.setIntArray = function (uniform, array) {
  95025. };
  95026. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95027. };
  95028. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95029. };
  95030. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95031. };
  95032. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95033. };
  95034. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95035. };
  95036. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95037. };
  95038. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95039. };
  95040. NullEngine.prototype.setArray = function (uniform, array) {
  95041. };
  95042. NullEngine.prototype.setArray2 = function (uniform, array) {
  95043. };
  95044. NullEngine.prototype.setArray3 = function (uniform, array) {
  95045. };
  95046. NullEngine.prototype.setArray4 = function (uniform, array) {
  95047. };
  95048. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95049. };
  95050. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95051. };
  95052. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95053. };
  95054. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95055. };
  95056. NullEngine.prototype.setFloat = function (uniform, value) {
  95057. };
  95058. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95059. };
  95060. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95061. };
  95062. NullEngine.prototype.setBool = function (uniform, bool) {
  95063. };
  95064. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95065. };
  95066. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95067. };
  95068. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95069. };
  95070. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95071. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95072. if (this._alphaMode === mode) {
  95073. return;
  95074. }
  95075. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95076. if (!noDepthWriteChange) {
  95077. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95078. }
  95079. this._alphaMode = mode;
  95080. };
  95081. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95082. };
  95083. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95084. if (this.preventCacheWipeBetweenFrames) {
  95085. return;
  95086. }
  95087. this.resetTextureCache();
  95088. this._currentEffect = null;
  95089. if (bruteForce) {
  95090. this._currentProgram = null;
  95091. this._stencilState.reset();
  95092. this._depthCullingState.reset();
  95093. this._alphaState.reset();
  95094. }
  95095. this._cachedVertexBuffers = null;
  95096. this._cachedIndexBuffer = null;
  95097. this._cachedEffectForVertexBuffers = null;
  95098. };
  95099. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95100. };
  95101. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95102. };
  95103. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95104. };
  95105. NullEngine.prototype._createTexture = function () {
  95106. return {};
  95107. };
  95108. NullEngine.prototype._releaseTexture = function (texture) {
  95109. };
  95110. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95112. if (onLoad === void 0) { onLoad = null; }
  95113. if (onError === void 0) { onError = null; }
  95114. if (buffer === void 0) { buffer = null; }
  95115. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95116. var url = String(urlArg);
  95117. texture.url = url;
  95118. texture.generateMipMaps = !noMipmap;
  95119. texture.samplingMode = samplingMode;
  95120. texture.invertY = invertY;
  95121. texture.baseWidth = this._options.textureSize;
  95122. texture.baseHeight = this._options.textureSize;
  95123. texture.width = this._options.textureSize;
  95124. texture.height = this._options.textureSize;
  95125. if (format) {
  95126. texture.format = format;
  95127. }
  95128. texture.isReady = true;
  95129. if (onLoad) {
  95130. onLoad();
  95131. }
  95132. return texture;
  95133. };
  95134. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95135. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95136. if (options !== undefined && typeof options === "object") {
  95137. fullOptions.generateMipMaps = options.generateMipMaps;
  95138. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95139. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95140. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95141. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95142. }
  95143. else {
  95144. fullOptions.generateMipMaps = options;
  95145. fullOptions.generateDepthBuffer = true;
  95146. fullOptions.generateStencilBuffer = false;
  95147. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95148. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95149. }
  95150. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95151. var width = size.width || size;
  95152. var height = size.height || size;
  95153. texture._depthStencilBuffer = {};
  95154. texture._framebuffer = {};
  95155. texture.baseWidth = width;
  95156. texture.baseHeight = height;
  95157. texture.width = width;
  95158. texture.height = height;
  95159. texture.isReady = true;
  95160. texture.samples = 1;
  95161. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95162. texture.samplingMode = fullOptions.samplingMode;
  95163. texture.type = fullOptions.type;
  95164. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95165. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95166. return texture;
  95167. };
  95168. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95169. texture.samplingMode = samplingMode;
  95170. };
  95171. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95172. if (this._currentRenderTarget) {
  95173. this.unBindFramebuffer(this._currentRenderTarget);
  95174. }
  95175. this._currentRenderTarget = texture;
  95176. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95177. if (this._cachedViewport && !forceFullscreenViewport) {
  95178. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95179. }
  95180. };
  95181. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95182. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95183. this._currentRenderTarget = null;
  95184. if (onBeforeUnbind) {
  95185. if (texture._MSAAFramebuffer) {
  95186. this._currentFramebuffer = texture._framebuffer;
  95187. }
  95188. onBeforeUnbind();
  95189. }
  95190. this._currentFramebuffer = null;
  95191. };
  95192. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95193. var vbo = {
  95194. capacity: 1,
  95195. references: 1,
  95196. is32Bits: false
  95197. };
  95198. return vbo;
  95199. };
  95200. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95201. if (offset === void 0) { offset = 0; }
  95202. };
  95203. /**
  95204. * Updates a dynamic vertex buffer.
  95205. * @param vertexBuffer the vertex buffer to update
  95206. * @param data the data used to update the vertex buffer
  95207. * @param byteOffset the byte offset of the data (optional)
  95208. * @param byteLength the byte length of the data (optional)
  95209. */
  95210. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95211. };
  95212. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95213. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95214. this._boundTexturesCache[this._activeChannel] = texture;
  95215. }
  95216. };
  95217. NullEngine.prototype._bindTexture = function (channel, texture) {
  95218. if (channel < 0) {
  95219. return;
  95220. }
  95221. this._bindTextureDirectly(0, texture);
  95222. };
  95223. NullEngine.prototype._releaseBuffer = function (buffer) {
  95224. buffer.references--;
  95225. if (buffer.references === 0) {
  95226. return true;
  95227. }
  95228. return false;
  95229. };
  95230. return NullEngine;
  95231. }(BABYLON.Engine));
  95232. BABYLON.NullEngine = NullEngine;
  95233. })(BABYLON || (BABYLON = {}));
  95234. //# sourceMappingURL=babylon.nullEngine.js.map
  95235. var BABYLON;
  95236. (function (BABYLON) {
  95237. /**
  95238. * This class can be used to get instrumentation data from a Babylon engine
  95239. */
  95240. var EngineInstrumentation = /** @class */ (function () {
  95241. function EngineInstrumentation(engine) {
  95242. this.engine = engine;
  95243. this._captureGPUFrameTime = false;
  95244. this._gpuFrameTime = new BABYLON.PerfCounter();
  95245. this._captureShaderCompilationTime = false;
  95246. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95247. // Observers
  95248. this._onBeginFrameObserver = null;
  95249. this._onEndFrameObserver = null;
  95250. this._onBeforeShaderCompilationObserver = null;
  95251. this._onAfterShaderCompilationObserver = null;
  95252. }
  95253. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95254. // Properties
  95255. /**
  95256. * Gets the perf counter used for GPU frame time
  95257. */
  95258. get: function () {
  95259. return this._gpuFrameTime;
  95260. },
  95261. enumerable: true,
  95262. configurable: true
  95263. });
  95264. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95265. /**
  95266. * Gets the GPU frame time capture status
  95267. */
  95268. get: function () {
  95269. return this._captureGPUFrameTime;
  95270. },
  95271. /**
  95272. * Enable or disable the GPU frame time capture
  95273. */
  95274. set: function (value) {
  95275. var _this = this;
  95276. if (value === this._captureGPUFrameTime) {
  95277. return;
  95278. }
  95279. this._captureGPUFrameTime = value;
  95280. if (value) {
  95281. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95282. if (!_this._gpuFrameTimeToken) {
  95283. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95284. }
  95285. });
  95286. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95287. if (!_this._gpuFrameTimeToken) {
  95288. return;
  95289. }
  95290. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95291. if (time > -1) {
  95292. _this._gpuFrameTimeToken = null;
  95293. _this._gpuFrameTime.fetchNewFrame();
  95294. _this._gpuFrameTime.addCount(time, true);
  95295. }
  95296. });
  95297. }
  95298. else {
  95299. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95300. this._onBeginFrameObserver = null;
  95301. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95302. this._onEndFrameObserver = null;
  95303. }
  95304. },
  95305. enumerable: true,
  95306. configurable: true
  95307. });
  95308. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95309. /**
  95310. * Gets the perf counter used for shader compilation time
  95311. */
  95312. get: function () {
  95313. return this._shaderCompilationTime;
  95314. },
  95315. enumerable: true,
  95316. configurable: true
  95317. });
  95318. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95319. /**
  95320. * Gets the shader compilation time capture status
  95321. */
  95322. get: function () {
  95323. return this._captureShaderCompilationTime;
  95324. },
  95325. /**
  95326. * Enable or disable the shader compilation time capture
  95327. */
  95328. set: function (value) {
  95329. var _this = this;
  95330. if (value === this._captureShaderCompilationTime) {
  95331. return;
  95332. }
  95333. this._captureShaderCompilationTime = value;
  95334. if (value) {
  95335. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95336. _this._shaderCompilationTime.fetchNewFrame();
  95337. _this._shaderCompilationTime.beginMonitoring();
  95338. });
  95339. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95340. _this._shaderCompilationTime.endMonitoring();
  95341. });
  95342. }
  95343. else {
  95344. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95345. this._onBeforeShaderCompilationObserver = null;
  95346. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95347. this._onAfterShaderCompilationObserver = null;
  95348. }
  95349. },
  95350. enumerable: true,
  95351. configurable: true
  95352. });
  95353. EngineInstrumentation.prototype.dispose = function () {
  95354. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95355. this._onBeginFrameObserver = null;
  95356. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95357. this._onEndFrameObserver = null;
  95358. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95359. this._onBeforeShaderCompilationObserver = null;
  95360. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95361. this._onAfterShaderCompilationObserver = null;
  95362. this.engine = null;
  95363. };
  95364. return EngineInstrumentation;
  95365. }());
  95366. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95367. })(BABYLON || (BABYLON = {}));
  95368. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95369. var BABYLON;
  95370. (function (BABYLON) {
  95371. /**
  95372. * This class can be used to get instrumentation data from a Babylon engine
  95373. */
  95374. var SceneInstrumentation = /** @class */ (function () {
  95375. function SceneInstrumentation(scene) {
  95376. var _this = this;
  95377. this.scene = scene;
  95378. this._captureActiveMeshesEvaluationTime = false;
  95379. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95380. this._captureRenderTargetsRenderTime = false;
  95381. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95382. this._captureFrameTime = false;
  95383. this._frameTime = new BABYLON.PerfCounter();
  95384. this._captureRenderTime = false;
  95385. this._renderTime = new BABYLON.PerfCounter();
  95386. this._captureInterFrameTime = false;
  95387. this._interFrameTime = new BABYLON.PerfCounter();
  95388. this._captureParticlesRenderTime = false;
  95389. this._particlesRenderTime = new BABYLON.PerfCounter();
  95390. this._captureSpritesRenderTime = false;
  95391. this._spritesRenderTime = new BABYLON.PerfCounter();
  95392. this._capturePhysicsTime = false;
  95393. this._physicsTime = new BABYLON.PerfCounter();
  95394. this._captureAnimationsTime = false;
  95395. this._animationsTime = new BABYLON.PerfCounter();
  95396. // Observers
  95397. this._onBeforeActiveMeshesEvaluationObserver = null;
  95398. this._onAfterActiveMeshesEvaluationObserver = null;
  95399. this._onBeforeRenderTargetsRenderObserver = null;
  95400. this._onAfterRenderTargetsRenderObserver = null;
  95401. this._onAfterRenderObserver = null;
  95402. this._onBeforeDrawPhaseObserver = null;
  95403. this._onAfterDrawPhaseObserver = null;
  95404. this._onBeforeAnimationsObserver = null;
  95405. this._onBeforeParticlesRenderingObserver = null;
  95406. this._onAfterParticlesRenderingObserver = null;
  95407. this._onBeforeSpritesRenderingObserver = null;
  95408. this._onAfterSpritesRenderingObserver = null;
  95409. this._onBeforePhysicsObserver = null;
  95410. this._onAfterPhysicsObserver = null;
  95411. this._onAfterAnimationsObserver = null;
  95412. // Before render
  95413. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95414. if (_this._captureActiveMeshesEvaluationTime) {
  95415. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95416. }
  95417. if (_this._captureRenderTargetsRenderTime) {
  95418. _this._renderTargetsRenderTime.fetchNewFrame();
  95419. }
  95420. if (_this._captureFrameTime) {
  95421. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95422. _this._frameTime.beginMonitoring();
  95423. }
  95424. if (_this._captureInterFrameTime) {
  95425. _this._interFrameTime.endMonitoring();
  95426. }
  95427. if (_this._captureParticlesRenderTime) {
  95428. _this._particlesRenderTime.fetchNewFrame();
  95429. }
  95430. if (_this._captureSpritesRenderTime) {
  95431. _this._spritesRenderTime.fetchNewFrame();
  95432. }
  95433. if (_this._captureAnimationsTime) {
  95434. _this._animationsTime.beginMonitoring();
  95435. }
  95436. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95437. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95438. });
  95439. // After render
  95440. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95441. if (_this._captureFrameTime) {
  95442. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95443. _this._frameTime.endMonitoring();
  95444. }
  95445. if (_this._captureRenderTime) {
  95446. _this._renderTime.endMonitoring(false);
  95447. }
  95448. if (_this._captureInterFrameTime) {
  95449. _this._interFrameTime.beginMonitoring();
  95450. }
  95451. });
  95452. }
  95453. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95454. // Properties
  95455. /**
  95456. * Gets the perf counter used for active meshes evaluation time
  95457. */
  95458. get: function () {
  95459. return this._activeMeshesEvaluationTime;
  95460. },
  95461. enumerable: true,
  95462. configurable: true
  95463. });
  95464. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95465. /**
  95466. * Gets the active meshes evaluation time capture status
  95467. */
  95468. get: function () {
  95469. return this._captureActiveMeshesEvaluationTime;
  95470. },
  95471. /**
  95472. * Enable or disable the active meshes evaluation time capture
  95473. */
  95474. set: function (value) {
  95475. var _this = this;
  95476. if (value === this._captureActiveMeshesEvaluationTime) {
  95477. return;
  95478. }
  95479. this._captureActiveMeshesEvaluationTime = value;
  95480. if (value) {
  95481. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95482. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95483. _this._activeMeshesEvaluationTime.beginMonitoring();
  95484. });
  95485. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95486. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95487. _this._activeMeshesEvaluationTime.endMonitoring();
  95488. });
  95489. }
  95490. else {
  95491. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95492. this._onBeforeActiveMeshesEvaluationObserver = null;
  95493. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95494. this._onAfterActiveMeshesEvaluationObserver = null;
  95495. }
  95496. },
  95497. enumerable: true,
  95498. configurable: true
  95499. });
  95500. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95501. /**
  95502. * Gets the perf counter used for render targets render time
  95503. */
  95504. get: function () {
  95505. return this._renderTargetsRenderTime;
  95506. },
  95507. enumerable: true,
  95508. configurable: true
  95509. });
  95510. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95511. /**
  95512. * Gets the render targets render time capture status
  95513. */
  95514. get: function () {
  95515. return this._captureRenderTargetsRenderTime;
  95516. },
  95517. /**
  95518. * Enable or disable the render targets render time capture
  95519. */
  95520. set: function (value) {
  95521. var _this = this;
  95522. if (value === this._captureRenderTargetsRenderTime) {
  95523. return;
  95524. }
  95525. this._captureRenderTargetsRenderTime = value;
  95526. if (value) {
  95527. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95528. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95529. _this._renderTargetsRenderTime.beginMonitoring();
  95530. });
  95531. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95532. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95533. _this._renderTargetsRenderTime.endMonitoring(false);
  95534. });
  95535. }
  95536. else {
  95537. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95538. this._onBeforeRenderTargetsRenderObserver = null;
  95539. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95540. this._onAfterRenderTargetsRenderObserver = null;
  95541. }
  95542. },
  95543. enumerable: true,
  95544. configurable: true
  95545. });
  95546. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95547. /**
  95548. * Gets the perf counter used for particles render time
  95549. */
  95550. get: function () {
  95551. return this._particlesRenderTime;
  95552. },
  95553. enumerable: true,
  95554. configurable: true
  95555. });
  95556. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95557. /**
  95558. * Gets the particles render time capture status
  95559. */
  95560. get: function () {
  95561. return this._captureParticlesRenderTime;
  95562. },
  95563. /**
  95564. * Enable or disable the particles render time capture
  95565. */
  95566. set: function (value) {
  95567. var _this = this;
  95568. if (value === this._captureParticlesRenderTime) {
  95569. return;
  95570. }
  95571. this._captureParticlesRenderTime = value;
  95572. if (value) {
  95573. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95574. BABYLON.Tools.StartPerformanceCounter("Particles");
  95575. _this._particlesRenderTime.beginMonitoring();
  95576. });
  95577. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95578. BABYLON.Tools.EndPerformanceCounter("Particles");
  95579. _this._particlesRenderTime.endMonitoring(false);
  95580. });
  95581. }
  95582. else {
  95583. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95584. this._onBeforeParticlesRenderingObserver = null;
  95585. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95586. this._onAfterParticlesRenderingObserver = null;
  95587. }
  95588. },
  95589. enumerable: true,
  95590. configurable: true
  95591. });
  95592. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95593. /**
  95594. * Gets the perf counter used for sprites render time
  95595. */
  95596. get: function () {
  95597. return this._spritesRenderTime;
  95598. },
  95599. enumerable: true,
  95600. configurable: true
  95601. });
  95602. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95603. /**
  95604. * Gets the sprites render time capture status
  95605. */
  95606. get: function () {
  95607. return this._captureSpritesRenderTime;
  95608. },
  95609. /**
  95610. * Enable or disable the sprites render time capture
  95611. */
  95612. set: function (value) {
  95613. var _this = this;
  95614. if (value === this._captureSpritesRenderTime) {
  95615. return;
  95616. }
  95617. this._captureSpritesRenderTime = value;
  95618. if (value) {
  95619. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95620. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95621. _this._spritesRenderTime.beginMonitoring();
  95622. });
  95623. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95624. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95625. _this._spritesRenderTime.endMonitoring(false);
  95626. });
  95627. }
  95628. else {
  95629. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95630. this._onBeforeSpritesRenderingObserver = null;
  95631. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95632. this._onAfterSpritesRenderingObserver = null;
  95633. }
  95634. },
  95635. enumerable: true,
  95636. configurable: true
  95637. });
  95638. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95639. /**
  95640. * Gets the perf counter used for physics time
  95641. */
  95642. get: function () {
  95643. return this._physicsTime;
  95644. },
  95645. enumerable: true,
  95646. configurable: true
  95647. });
  95648. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95649. /**
  95650. * Gets the physics time capture status
  95651. */
  95652. get: function () {
  95653. return this._capturePhysicsTime;
  95654. },
  95655. /**
  95656. * Enable or disable the physics time capture
  95657. */
  95658. set: function (value) {
  95659. var _this = this;
  95660. if (value === this._capturePhysicsTime) {
  95661. return;
  95662. }
  95663. this._capturePhysicsTime = value;
  95664. if (value) {
  95665. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95666. BABYLON.Tools.StartPerformanceCounter("Physics");
  95667. _this._physicsTime.beginMonitoring();
  95668. });
  95669. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95670. BABYLON.Tools.EndPerformanceCounter("Physics");
  95671. _this._physicsTime.endMonitoring();
  95672. });
  95673. }
  95674. else {
  95675. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95676. this._onBeforePhysicsObserver = null;
  95677. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95678. this._onAfterPhysicsObserver = null;
  95679. }
  95680. },
  95681. enumerable: true,
  95682. configurable: true
  95683. });
  95684. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95685. /**
  95686. * Gets the perf counter used for animations time
  95687. */
  95688. get: function () {
  95689. return this._animationsTime;
  95690. },
  95691. enumerable: true,
  95692. configurable: true
  95693. });
  95694. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95695. /**
  95696. * Gets the animations time capture status
  95697. */
  95698. get: function () {
  95699. return this._captureAnimationsTime;
  95700. },
  95701. /**
  95702. * Enable or disable the animations time capture
  95703. */
  95704. set: function (value) {
  95705. var _this = this;
  95706. if (value === this._captureAnimationsTime) {
  95707. return;
  95708. }
  95709. this._captureAnimationsTime = value;
  95710. if (value) {
  95711. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95712. _this._animationsTime.endMonitoring();
  95713. });
  95714. }
  95715. else {
  95716. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95717. this._onAfterAnimationsObserver = null;
  95718. }
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95724. /**
  95725. * Gets the perf counter used for frame time capture
  95726. */
  95727. get: function () {
  95728. return this._frameTime;
  95729. },
  95730. enumerable: true,
  95731. configurable: true
  95732. });
  95733. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95734. /**
  95735. * Gets the frame time capture status
  95736. */
  95737. get: function () {
  95738. return this._captureFrameTime;
  95739. },
  95740. /**
  95741. * Enable or disable the frame time capture
  95742. */
  95743. set: function (value) {
  95744. this._captureFrameTime = value;
  95745. },
  95746. enumerable: true,
  95747. configurable: true
  95748. });
  95749. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95750. /**
  95751. * Gets the perf counter used for inter-frames time capture
  95752. */
  95753. get: function () {
  95754. return this._interFrameTime;
  95755. },
  95756. enumerable: true,
  95757. configurable: true
  95758. });
  95759. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95760. /**
  95761. * Gets the inter-frames time capture status
  95762. */
  95763. get: function () {
  95764. return this._captureInterFrameTime;
  95765. },
  95766. /**
  95767. * Enable or disable the inter-frames time capture
  95768. */
  95769. set: function (value) {
  95770. this._captureInterFrameTime = value;
  95771. },
  95772. enumerable: true,
  95773. configurable: true
  95774. });
  95775. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95776. /**
  95777. * Gets the perf counter used for render time capture
  95778. */
  95779. get: function () {
  95780. return this._renderTime;
  95781. },
  95782. enumerable: true,
  95783. configurable: true
  95784. });
  95785. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95786. /**
  95787. * Gets the render time capture status
  95788. */
  95789. get: function () {
  95790. return this._captureRenderTime;
  95791. },
  95792. /**
  95793. * Enable or disable the render time capture
  95794. */
  95795. set: function (value) {
  95796. var _this = this;
  95797. if (value === this._captureRenderTime) {
  95798. return;
  95799. }
  95800. this._captureRenderTime = value;
  95801. if (value) {
  95802. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95803. _this._renderTime.beginMonitoring();
  95804. BABYLON.Tools.StartPerformanceCounter("Main render");
  95805. });
  95806. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95807. _this._renderTime.endMonitoring(false);
  95808. BABYLON.Tools.EndPerformanceCounter("Main render");
  95809. });
  95810. }
  95811. else {
  95812. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95813. this._onBeforeDrawPhaseObserver = null;
  95814. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95815. this._onAfterDrawPhaseObserver = null;
  95816. }
  95817. },
  95818. enumerable: true,
  95819. configurable: true
  95820. });
  95821. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95822. /**
  95823. * Gets the perf counter used for draw calls
  95824. */
  95825. get: function () {
  95826. return this.scene.getEngine()._drawCalls;
  95827. },
  95828. enumerable: true,
  95829. configurable: true
  95830. });
  95831. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95832. /**
  95833. * Gets the perf counter used for texture collisions
  95834. */
  95835. get: function () {
  95836. return this.scene.getEngine()._textureCollisions;
  95837. },
  95838. enumerable: true,
  95839. configurable: true
  95840. });
  95841. SceneInstrumentation.prototype.dispose = function () {
  95842. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95843. this._onAfterRenderObserver = null;
  95844. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95845. this._onBeforeActiveMeshesEvaluationObserver = null;
  95846. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95847. this._onAfterActiveMeshesEvaluationObserver = null;
  95848. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95849. this._onBeforeRenderTargetsRenderObserver = null;
  95850. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95851. this._onAfterRenderTargetsRenderObserver = null;
  95852. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95853. this._onBeforeAnimationsObserver = null;
  95854. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95855. this._onBeforeParticlesRenderingObserver = null;
  95856. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95857. this._onAfterParticlesRenderingObserver = null;
  95858. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95859. this._onBeforeSpritesRenderingObserver = null;
  95860. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95861. this._onAfterSpritesRenderingObserver = null;
  95862. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95863. this._onBeforeDrawPhaseObserver = null;
  95864. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95865. this._onAfterDrawPhaseObserver = null;
  95866. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95867. this._onBeforePhysicsObserver = null;
  95868. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95869. this._onAfterPhysicsObserver = null;
  95870. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95871. this._onAfterAnimationsObserver = null;
  95872. this.scene = null;
  95873. };
  95874. return SceneInstrumentation;
  95875. }());
  95876. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95877. })(BABYLON || (BABYLON = {}));
  95878. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95879. var BABYLON;
  95880. (function (BABYLON) {
  95881. /**
  95882. * @hidden
  95883. **/
  95884. var _TimeToken = /** @class */ (function () {
  95885. function _TimeToken() {
  95886. this._timeElapsedQueryEnded = false;
  95887. }
  95888. return _TimeToken;
  95889. }());
  95890. BABYLON._TimeToken = _TimeToken;
  95891. })(BABYLON || (BABYLON = {}));
  95892. //# sourceMappingURL=babylon.timeToken.js.map
  95893. var BABYLON;
  95894. (function (BABYLON) {
  95895. /**
  95896. * Background material defines definition.
  95897. * @hidden Mainly internal Use
  95898. */
  95899. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95900. __extends(BackgroundMaterialDefines, _super);
  95901. /**
  95902. * Constructor of the defines.
  95903. */
  95904. function BackgroundMaterialDefines() {
  95905. var _this = _super.call(this) || this;
  95906. /**
  95907. * True if the diffuse texture is in use.
  95908. */
  95909. _this.DIFFUSE = false;
  95910. /**
  95911. * The direct UV channel to use.
  95912. */
  95913. _this.DIFFUSEDIRECTUV = 0;
  95914. /**
  95915. * True if the diffuse texture is in gamma space.
  95916. */
  95917. _this.GAMMADIFFUSE = false;
  95918. /**
  95919. * True if the diffuse texture has opacity in the alpha channel.
  95920. */
  95921. _this.DIFFUSEHASALPHA = false;
  95922. /**
  95923. * True if you want the material to fade to transparent at grazing angle.
  95924. */
  95925. _this.OPACITYFRESNEL = false;
  95926. /**
  95927. * True if an extra blur needs to be added in the reflection.
  95928. */
  95929. _this.REFLECTIONBLUR = false;
  95930. /**
  95931. * True if you want the material to fade to reflection at grazing angle.
  95932. */
  95933. _this.REFLECTIONFRESNEL = false;
  95934. /**
  95935. * True if you want the material to falloff as far as you move away from the scene center.
  95936. */
  95937. _this.REFLECTIONFALLOFF = false;
  95938. /**
  95939. * False if the current Webgl implementation does not support the texture lod extension.
  95940. */
  95941. _this.TEXTURELODSUPPORT = false;
  95942. /**
  95943. * True to ensure the data are premultiplied.
  95944. */
  95945. _this.PREMULTIPLYALPHA = false;
  95946. /**
  95947. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95948. */
  95949. _this.USERGBCOLOR = false;
  95950. /**
  95951. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95952. * stays aligned with the desired configuration.
  95953. */
  95954. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95955. /**
  95956. * True to add noise in order to reduce the banding effect.
  95957. */
  95958. _this.NOISE = false;
  95959. /**
  95960. * is the reflection texture in BGR color scheme?
  95961. * Mainly used to solve a bug in ios10 video tag
  95962. */
  95963. _this.REFLECTIONBGR = false;
  95964. _this.IMAGEPROCESSING = false;
  95965. _this.VIGNETTE = false;
  95966. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95967. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95968. _this.TONEMAPPING = false;
  95969. _this.CONTRAST = false;
  95970. _this.COLORCURVES = false;
  95971. _this.COLORGRADING = false;
  95972. _this.COLORGRADING3D = false;
  95973. _this.SAMPLER3DGREENDEPTH = false;
  95974. _this.SAMPLER3DBGRMAP = false;
  95975. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95976. _this.EXPOSURE = false;
  95977. // Reflection.
  95978. _this.REFLECTION = false;
  95979. _this.REFLECTIONMAP_3D = false;
  95980. _this.REFLECTIONMAP_SPHERICAL = false;
  95981. _this.REFLECTIONMAP_PLANAR = false;
  95982. _this.REFLECTIONMAP_CUBIC = false;
  95983. _this.REFLECTIONMAP_PROJECTION = false;
  95984. _this.REFLECTIONMAP_SKYBOX = false;
  95985. _this.REFLECTIONMAP_EXPLICIT = false;
  95986. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95987. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95988. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95989. _this.INVERTCUBICMAP = false;
  95990. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95991. _this.LODINREFLECTIONALPHA = false;
  95992. _this.GAMMAREFLECTION = false;
  95993. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95994. // Default BJS.
  95995. _this.MAINUV1 = false;
  95996. _this.MAINUV2 = false;
  95997. _this.UV1 = false;
  95998. _this.UV2 = false;
  95999. _this.CLIPPLANE = false;
  96000. _this.POINTSIZE = false;
  96001. _this.FOG = false;
  96002. _this.NORMAL = false;
  96003. _this.NUM_BONE_INFLUENCERS = 0;
  96004. _this.BonesPerMesh = 0;
  96005. _this.INSTANCES = false;
  96006. _this.SHADOWFLOAT = false;
  96007. _this.rebuild();
  96008. return _this;
  96009. }
  96010. return BackgroundMaterialDefines;
  96011. }(BABYLON.MaterialDefines));
  96012. /**
  96013. * Background material used to create an efficient environement around your scene.
  96014. */
  96015. var BackgroundMaterial = /** @class */ (function (_super) {
  96016. __extends(BackgroundMaterial, _super);
  96017. /**
  96018. * Instantiates a Background Material in the given scene
  96019. * @param name The friendly name of the material
  96020. * @param scene The scene to add the material to
  96021. */
  96022. function BackgroundMaterial(name, scene) {
  96023. var _this = _super.call(this, name, scene) || this;
  96024. /**
  96025. * Key light Color (multiply against the environement texture)
  96026. */
  96027. _this.primaryColor = BABYLON.Color3.White();
  96028. _this._primaryColorShadowLevel = 0;
  96029. _this._primaryColorHighlightLevel = 0;
  96030. /**
  96031. * Reflection Texture used in the material.
  96032. * Should be author in a specific way for the best result (refer to the documentation).
  96033. */
  96034. _this.reflectionTexture = null;
  96035. /**
  96036. * Reflection Texture level of blur.
  96037. *
  96038. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96039. * texture twice.
  96040. */
  96041. _this.reflectionBlur = 0;
  96042. /**
  96043. * Diffuse Texture used in the material.
  96044. * Should be author in a specific way for the best result (refer to the documentation).
  96045. */
  96046. _this.diffuseTexture = null;
  96047. _this._shadowLights = null;
  96048. /**
  96049. * Specify the list of lights casting shadow on the material.
  96050. * All scene shadow lights will be included if null.
  96051. */
  96052. _this.shadowLights = null;
  96053. /**
  96054. * Helps adjusting the shadow to a softer level if required.
  96055. * 0 means black shadows and 1 means no shadows.
  96056. */
  96057. _this.shadowLevel = 0;
  96058. /**
  96059. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96060. * It is usually zero but might be interesting to modify according to your setup.
  96061. */
  96062. _this.sceneCenter = BABYLON.Vector3.Zero();
  96063. /**
  96064. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96065. * This helps ensuring a nice transition when the camera goes under the ground.
  96066. */
  96067. _this.opacityFresnel = true;
  96068. /**
  96069. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96070. * This helps adding a mirror texture on the ground.
  96071. */
  96072. _this.reflectionFresnel = false;
  96073. /**
  96074. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96075. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96076. */
  96077. _this.reflectionFalloffDistance = 0.0;
  96078. /**
  96079. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96080. */
  96081. _this.reflectionAmount = 1.0;
  96082. /**
  96083. * This specifies the weight of the reflection at grazing angle.
  96084. */
  96085. _this.reflectionReflectance0 = 0.05;
  96086. /**
  96087. * This specifies the weight of the reflection at a perpendicular point of view.
  96088. */
  96089. _this.reflectionReflectance90 = 0.5;
  96090. /**
  96091. * Helps to directly use the maps channels instead of their level.
  96092. */
  96093. _this.useRGBColor = true;
  96094. /**
  96095. * This helps reducing the banding effect that could occur on the background.
  96096. */
  96097. _this.enableNoise = false;
  96098. _this._fovMultiplier = 1.0;
  96099. /**
  96100. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96101. */
  96102. _this.useEquirectangularFOV = false;
  96103. _this._maxSimultaneousLights = 4;
  96104. /**
  96105. * Number of Simultaneous lights allowed on the material.
  96106. */
  96107. _this.maxSimultaneousLights = 4;
  96108. /**
  96109. * Keep track of the image processing observer to allow dispose and replace.
  96110. */
  96111. _this._imageProcessingObserver = null;
  96112. /**
  96113. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96114. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96115. */
  96116. _this.switchToBGR = false;
  96117. // Temp values kept as cache in the material.
  96118. _this._renderTargets = new BABYLON.SmartArray(16);
  96119. _this._reflectionControls = BABYLON.Vector4.Zero();
  96120. _this._white = BABYLON.Color3.White();
  96121. _this._primaryShadowColor = BABYLON.Color3.Black();
  96122. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96123. // Setup the default processing configuration to the scene.
  96124. _this._attachImageProcessingConfiguration(null);
  96125. _this.getRenderTargetTextures = function () {
  96126. _this._renderTargets.reset();
  96127. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96128. _this._renderTargets.push(_this._diffuseTexture);
  96129. }
  96130. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96131. _this._renderTargets.push(_this._reflectionTexture);
  96132. }
  96133. return _this._renderTargets;
  96134. };
  96135. return _this;
  96136. }
  96137. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96138. /**
  96139. * Experimental Internal Use Only.
  96140. *
  96141. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96142. * This acts as a helper to set the primary color to a more "human friendly" value.
  96143. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96144. * output color as close as possible from the chosen value.
  96145. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96146. * part of lighting setup.)
  96147. */
  96148. get: function () {
  96149. return this.__perceptualColor;
  96150. },
  96151. set: function (value) {
  96152. this.__perceptualColor = value;
  96153. this._computePrimaryColorFromPerceptualColor();
  96154. this._markAllSubMeshesAsLightsDirty();
  96155. },
  96156. enumerable: true,
  96157. configurable: true
  96158. });
  96159. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96160. /**
  96161. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96162. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96163. */
  96164. get: function () {
  96165. return this._primaryColorShadowLevel;
  96166. },
  96167. set: function (value) {
  96168. this._primaryColorShadowLevel = value;
  96169. this._computePrimaryColors();
  96170. this._markAllSubMeshesAsLightsDirty();
  96171. },
  96172. enumerable: true,
  96173. configurable: true
  96174. });
  96175. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96176. /**
  96177. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96178. * The primary color is used at the level chosen to define what the white area would look.
  96179. */
  96180. get: function () {
  96181. return this._primaryColorHighlightLevel;
  96182. },
  96183. set: function (value) {
  96184. this._primaryColorHighlightLevel = value;
  96185. this._computePrimaryColors();
  96186. this._markAllSubMeshesAsLightsDirty();
  96187. },
  96188. enumerable: true,
  96189. configurable: true
  96190. });
  96191. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96192. /**
  96193. * Sets the reflection reflectance fresnel values according to the default standard
  96194. * empirically know to work well :-)
  96195. */
  96196. set: function (value) {
  96197. var reflectionWeight = value;
  96198. if (reflectionWeight < 0.5) {
  96199. reflectionWeight = reflectionWeight * 2.0;
  96200. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96201. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96202. }
  96203. else {
  96204. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96205. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96206. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96207. }
  96208. },
  96209. enumerable: true,
  96210. configurable: true
  96211. });
  96212. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96213. /**
  96214. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96215. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96216. * Recommended to be keep at 1.0 except for special cases.
  96217. */
  96218. get: function () {
  96219. return this._fovMultiplier;
  96220. },
  96221. set: function (value) {
  96222. if (isNaN(value)) {
  96223. value = 1.0;
  96224. }
  96225. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96226. },
  96227. enumerable: true,
  96228. configurable: true
  96229. });
  96230. /**
  96231. * Attaches a new image processing configuration to the PBR Material.
  96232. * @param configuration (if null the scene configuration will be use)
  96233. */
  96234. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96235. var _this = this;
  96236. if (configuration === this._imageProcessingConfiguration) {
  96237. return;
  96238. }
  96239. // Detaches observer.
  96240. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96241. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96242. }
  96243. // Pick the scene configuration if needed.
  96244. if (!configuration) {
  96245. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96246. }
  96247. else {
  96248. this._imageProcessingConfiguration = configuration;
  96249. }
  96250. // Attaches observer.
  96251. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96252. _this._computePrimaryColorFromPerceptualColor();
  96253. _this._markAllSubMeshesAsImageProcessingDirty();
  96254. });
  96255. };
  96256. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96257. /**
  96258. * Gets the image processing configuration used either in this material.
  96259. */
  96260. get: function () {
  96261. return this._imageProcessingConfiguration;
  96262. },
  96263. /**
  96264. * Sets the Default image processing configuration used either in the this material.
  96265. *
  96266. * If sets to null, the scene one is in use.
  96267. */
  96268. set: function (value) {
  96269. this._attachImageProcessingConfiguration(value);
  96270. // Ensure the effect will be rebuilt.
  96271. this._markAllSubMeshesAsTexturesDirty();
  96272. },
  96273. enumerable: true,
  96274. configurable: true
  96275. });
  96276. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96277. /**
  96278. * Gets wether the color curves effect is enabled.
  96279. */
  96280. get: function () {
  96281. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96282. },
  96283. /**
  96284. * Sets wether the color curves effect is enabled.
  96285. */
  96286. set: function (value) {
  96287. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96288. },
  96289. enumerable: true,
  96290. configurable: true
  96291. });
  96292. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96293. /**
  96294. * Gets wether the color grading effect is enabled.
  96295. */
  96296. get: function () {
  96297. return this.imageProcessingConfiguration.colorGradingEnabled;
  96298. },
  96299. /**
  96300. * Gets wether the color grading effect is enabled.
  96301. */
  96302. set: function (value) {
  96303. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96304. },
  96305. enumerable: true,
  96306. configurable: true
  96307. });
  96308. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96309. /**
  96310. * Gets wether tonemapping is enabled or not.
  96311. */
  96312. get: function () {
  96313. return this._imageProcessingConfiguration.toneMappingEnabled;
  96314. },
  96315. /**
  96316. * Sets wether tonemapping is enabled or not
  96317. */
  96318. set: function (value) {
  96319. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96320. },
  96321. enumerable: true,
  96322. configurable: true
  96323. });
  96324. ;
  96325. ;
  96326. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96327. /**
  96328. * The camera exposure used on this material.
  96329. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96330. * This corresponds to a photographic exposure.
  96331. */
  96332. get: function () {
  96333. return this._imageProcessingConfiguration.exposure;
  96334. },
  96335. /**
  96336. * The camera exposure used on this material.
  96337. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96338. * This corresponds to a photographic exposure.
  96339. */
  96340. set: function (value) {
  96341. this._imageProcessingConfiguration.exposure = value;
  96342. },
  96343. enumerable: true,
  96344. configurable: true
  96345. });
  96346. ;
  96347. ;
  96348. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96349. /**
  96350. * Gets The camera contrast used on this material.
  96351. */
  96352. get: function () {
  96353. return this._imageProcessingConfiguration.contrast;
  96354. },
  96355. /**
  96356. * Sets The camera contrast used on this material.
  96357. */
  96358. set: function (value) {
  96359. this._imageProcessingConfiguration.contrast = value;
  96360. },
  96361. enumerable: true,
  96362. configurable: true
  96363. });
  96364. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96365. /**
  96366. * Gets the Color Grading 2D Lookup Texture.
  96367. */
  96368. get: function () {
  96369. return this._imageProcessingConfiguration.colorGradingTexture;
  96370. },
  96371. /**
  96372. * Sets the Color Grading 2D Lookup Texture.
  96373. */
  96374. set: function (value) {
  96375. this.imageProcessingConfiguration.colorGradingTexture = value;
  96376. },
  96377. enumerable: true,
  96378. configurable: true
  96379. });
  96380. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96381. /**
  96382. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96383. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96384. * 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;
  96385. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96386. */
  96387. get: function () {
  96388. return this.imageProcessingConfiguration.colorCurves;
  96389. },
  96390. /**
  96391. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96392. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96393. * 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;
  96394. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96395. */
  96396. set: function (value) {
  96397. this.imageProcessingConfiguration.colorCurves = value;
  96398. },
  96399. enumerable: true,
  96400. configurable: true
  96401. });
  96402. /**
  96403. * The entire material has been created in order to prevent overdraw.
  96404. * @returns false
  96405. */
  96406. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96407. return true;
  96408. };
  96409. /**
  96410. * The entire material has been created in order to prevent overdraw.
  96411. * @returns true if blending is enable
  96412. */
  96413. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96414. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96415. };
  96416. /**
  96417. * Checks wether the material is ready to be rendered for a given mesh.
  96418. * @param mesh The mesh to render
  96419. * @param subMesh The submesh to check against
  96420. * @param useInstances Specify wether or not the material is used with instances
  96421. * @returns true if all the dependencies are ready (Textures, Effects...)
  96422. */
  96423. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96424. var _this = this;
  96425. if (useInstances === void 0) { useInstances = false; }
  96426. if (subMesh.effect && this.isFrozen) {
  96427. if (this._wasPreviouslyReady) {
  96428. return true;
  96429. }
  96430. }
  96431. if (!subMesh._materialDefines) {
  96432. subMesh._materialDefines = new BackgroundMaterialDefines();
  96433. }
  96434. var scene = this.getScene();
  96435. var defines = subMesh._materialDefines;
  96436. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96437. if (defines._renderId === scene.getRenderId()) {
  96438. return true;
  96439. }
  96440. }
  96441. var engine = scene.getEngine();
  96442. // Lights
  96443. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96444. defines._needNormals = true;
  96445. // Textures
  96446. if (defines._areTexturesDirty) {
  96447. defines._needUVs = false;
  96448. if (scene.texturesEnabled) {
  96449. if (scene.getEngine().getCaps().textureLOD) {
  96450. defines.TEXTURELODSUPPORT = true;
  96451. }
  96452. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96453. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96454. return false;
  96455. }
  96456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96457. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96458. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96459. defines.OPACITYFRESNEL = this._opacityFresnel;
  96460. }
  96461. else {
  96462. defines.DIFFUSE = false;
  96463. defines.DIFFUSEHASALPHA = false;
  96464. defines.GAMMADIFFUSE = false;
  96465. defines.OPACITYFRESNEL = false;
  96466. }
  96467. var reflectionTexture = this._reflectionTexture;
  96468. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96469. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96470. return false;
  96471. }
  96472. defines.REFLECTION = true;
  96473. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96474. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96475. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96476. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96477. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96478. defines.REFLECTIONBGR = this.switchToBGR;
  96479. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96480. defines.INVERTCUBICMAP = true;
  96481. }
  96482. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96483. switch (reflectionTexture.coordinatesMode) {
  96484. case BABYLON.Texture.CUBIC_MODE:
  96485. case BABYLON.Texture.INVCUBIC_MODE:
  96486. defines.REFLECTIONMAP_CUBIC = true;
  96487. break;
  96488. case BABYLON.Texture.EXPLICIT_MODE:
  96489. defines.REFLECTIONMAP_EXPLICIT = true;
  96490. break;
  96491. case BABYLON.Texture.PLANAR_MODE:
  96492. defines.REFLECTIONMAP_PLANAR = true;
  96493. break;
  96494. case BABYLON.Texture.PROJECTION_MODE:
  96495. defines.REFLECTIONMAP_PROJECTION = true;
  96496. break;
  96497. case BABYLON.Texture.SKYBOX_MODE:
  96498. defines.REFLECTIONMAP_SKYBOX = true;
  96499. break;
  96500. case BABYLON.Texture.SPHERICAL_MODE:
  96501. defines.REFLECTIONMAP_SPHERICAL = true;
  96502. break;
  96503. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96504. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96505. break;
  96506. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96507. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96508. break;
  96509. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96510. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96511. break;
  96512. }
  96513. if (this.reflectionFresnel) {
  96514. defines.REFLECTIONFRESNEL = true;
  96515. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96516. this._reflectionControls.x = this.reflectionAmount;
  96517. this._reflectionControls.y = this.reflectionReflectance0;
  96518. this._reflectionControls.z = this.reflectionReflectance90;
  96519. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96520. }
  96521. else {
  96522. defines.REFLECTIONFRESNEL = false;
  96523. defines.REFLECTIONFALLOFF = false;
  96524. }
  96525. }
  96526. else {
  96527. defines.REFLECTION = false;
  96528. defines.REFLECTIONFRESNEL = false;
  96529. defines.REFLECTIONFALLOFF = false;
  96530. defines.REFLECTIONBLUR = false;
  96531. defines.REFLECTIONMAP_3D = false;
  96532. defines.REFLECTIONMAP_SPHERICAL = false;
  96533. defines.REFLECTIONMAP_PLANAR = false;
  96534. defines.REFLECTIONMAP_CUBIC = false;
  96535. defines.REFLECTIONMAP_PROJECTION = false;
  96536. defines.REFLECTIONMAP_SKYBOX = false;
  96537. defines.REFLECTIONMAP_EXPLICIT = false;
  96538. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96539. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96540. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96541. defines.INVERTCUBICMAP = false;
  96542. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96543. defines.LODINREFLECTIONALPHA = false;
  96544. defines.GAMMAREFLECTION = false;
  96545. }
  96546. }
  96547. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96548. defines.USERGBCOLOR = this._useRGBColor;
  96549. defines.NOISE = this._enableNoise;
  96550. }
  96551. if (defines._areLightsDirty) {
  96552. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96553. }
  96554. if (defines._areImageProcessingDirty) {
  96555. if (!this._imageProcessingConfiguration.isReady()) {
  96556. return false;
  96557. }
  96558. this._imageProcessingConfiguration.prepareDefines(defines);
  96559. }
  96560. // Misc.
  96561. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96562. // Values that need to be evaluated on every frame
  96563. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96564. // Attribs
  96565. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96566. if (mesh) {
  96567. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96568. mesh.createNormals(true);
  96569. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96570. }
  96571. }
  96572. }
  96573. // Get correct effect
  96574. if (defines.isDirty) {
  96575. defines.markAsProcessed();
  96576. scene.resetCachedMaterial();
  96577. // Fallbacks
  96578. var fallbacks = new BABYLON.EffectFallbacks();
  96579. if (defines.FOG) {
  96580. fallbacks.addFallback(0, "FOG");
  96581. }
  96582. if (defines.POINTSIZE) {
  96583. fallbacks.addFallback(1, "POINTSIZE");
  96584. }
  96585. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96586. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96587. fallbacks.addCPUSkinningFallback(0, mesh);
  96588. }
  96589. //Attributes
  96590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96591. if (defines.NORMAL) {
  96592. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96593. }
  96594. if (defines.UV1) {
  96595. attribs.push(BABYLON.VertexBuffer.UVKind);
  96596. }
  96597. if (defines.UV2) {
  96598. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96599. }
  96600. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96601. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96602. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96603. "vFogInfos", "vFogColor", "pointSize",
  96604. "vClipPlane", "mBones",
  96605. "vPrimaryColor", "vPrimaryColorShadow",
  96606. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96607. "shadowLevel", "alpha",
  96608. "vBackgroundCenter", "vReflectionControl",
  96609. "vDiffuseInfos", "diffuseMatrix",
  96610. ];
  96611. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96612. var uniformBuffers = ["Material", "Scene"];
  96613. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96614. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96615. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96616. uniformsNames: uniforms,
  96617. uniformBuffersNames: uniformBuffers,
  96618. samplers: samplers,
  96619. defines: defines,
  96620. maxSimultaneousLights: this._maxSimultaneousLights
  96621. });
  96622. var onCompiled = function (effect) {
  96623. if (_this.onCompiled) {
  96624. _this.onCompiled(effect);
  96625. }
  96626. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96627. };
  96628. var join = defines.toString();
  96629. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96630. attributes: attribs,
  96631. uniformsNames: uniforms,
  96632. uniformBuffersNames: uniformBuffers,
  96633. samplers: samplers,
  96634. defines: join,
  96635. fallbacks: fallbacks,
  96636. onCompiled: onCompiled,
  96637. onError: this.onError,
  96638. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96639. }, engine), defines);
  96640. this.buildUniformLayout();
  96641. }
  96642. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96643. return false;
  96644. }
  96645. defines._renderId = scene.getRenderId();
  96646. this._wasPreviouslyReady = true;
  96647. return true;
  96648. };
  96649. /**
  96650. * Compute the primary color according to the chosen perceptual color.
  96651. */
  96652. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96653. if (!this.__perceptualColor) {
  96654. return;
  96655. }
  96656. this._primaryColor.copyFrom(this.__perceptualColor);
  96657. // Revert gamma space.
  96658. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96659. // Revert image processing configuration.
  96660. if (this._imageProcessingConfiguration) {
  96661. // Revert Exposure.
  96662. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96663. }
  96664. this._computePrimaryColors();
  96665. };
  96666. /**
  96667. * Compute the highlights and shadow colors according to their chosen levels.
  96668. */
  96669. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96670. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96671. return;
  96672. }
  96673. // Find the highlight color based on the configuration.
  96674. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96675. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96676. // Find the shadow color based on the configuration.
  96677. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96678. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96679. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96680. };
  96681. /**
  96682. * Build the uniform buffer used in the material.
  96683. */
  96684. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96685. // Order is important !
  96686. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96687. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96688. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96689. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96690. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96691. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96692. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96693. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96694. this._uniformBuffer.addUniform("pointSize", 1);
  96695. this._uniformBuffer.addUniform("shadowLevel", 1);
  96696. this._uniformBuffer.addUniform("alpha", 1);
  96697. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96698. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96699. this._uniformBuffer.create();
  96700. };
  96701. /**
  96702. * Unbind the material.
  96703. */
  96704. BackgroundMaterial.prototype.unbind = function () {
  96705. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96706. this._uniformBuffer.setTexture("diffuseSampler", null);
  96707. }
  96708. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96709. this._uniformBuffer.setTexture("reflectionSampler", null);
  96710. }
  96711. _super.prototype.unbind.call(this);
  96712. };
  96713. /**
  96714. * Bind only the world matrix to the material.
  96715. * @param world The world matrix to bind.
  96716. */
  96717. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96718. this._activeEffect.setMatrix("world", world);
  96719. };
  96720. /**
  96721. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96722. * @param world The world matrix to bind.
  96723. * @param subMesh The submesh to bind for.
  96724. */
  96725. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96726. var scene = this.getScene();
  96727. var defines = subMesh._materialDefines;
  96728. if (!defines) {
  96729. return;
  96730. }
  96731. var effect = subMesh.effect;
  96732. if (!effect) {
  96733. return;
  96734. }
  96735. this._activeEffect = effect;
  96736. // Matrices
  96737. this.bindOnlyWorldMatrix(world);
  96738. // Bones
  96739. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96740. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96741. if (mustRebind) {
  96742. this._uniformBuffer.bindToEffect(effect, "Material");
  96743. this.bindViewProjection(effect);
  96744. var reflectionTexture = this._reflectionTexture;
  96745. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96746. // Texture uniforms
  96747. if (scene.texturesEnabled) {
  96748. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96749. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96750. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96751. }
  96752. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96753. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96754. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96755. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96756. }
  96757. }
  96758. if (this.shadowLevel > 0) {
  96759. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96760. }
  96761. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96762. // Point size
  96763. if (this.pointsCloud) {
  96764. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96765. }
  96766. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96767. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96768. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96769. }
  96770. else {
  96771. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96772. }
  96773. }
  96774. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96775. // Textures
  96776. if (scene.texturesEnabled) {
  96777. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96778. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96779. }
  96780. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96781. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96782. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96783. }
  96784. else if (!defines.REFLECTIONBLUR) {
  96785. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96786. }
  96787. else {
  96788. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96789. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96790. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96791. }
  96792. if (defines.REFLECTIONFRESNEL) {
  96793. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96794. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96795. }
  96796. }
  96797. }
  96798. // Clip plane
  96799. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96800. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96801. }
  96802. if (mustRebind || !this.isFrozen) {
  96803. if (scene.lightsEnabled) {
  96804. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96805. }
  96806. // View
  96807. this.bindView(effect);
  96808. // Fog
  96809. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96810. // image processing
  96811. this._imageProcessingConfiguration.bind(this._activeEffect);
  96812. }
  96813. this._uniformBuffer.update();
  96814. this._afterBind(mesh);
  96815. };
  96816. /**
  96817. * Dispose the material.
  96818. * @param forceDisposeEffect Force disposal of the associated effect.
  96819. * @param forceDisposeTextures Force disposal of the associated textures.
  96820. */
  96821. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96822. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96823. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96824. if (forceDisposeTextures) {
  96825. if (this.diffuseTexture) {
  96826. this.diffuseTexture.dispose();
  96827. }
  96828. if (this.reflectionTexture) {
  96829. this.reflectionTexture.dispose();
  96830. }
  96831. }
  96832. this._renderTargets.dispose();
  96833. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96834. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96835. }
  96836. _super.prototype.dispose.call(this, forceDisposeEffect);
  96837. };
  96838. /**
  96839. * Clones the material.
  96840. * @param name The cloned name.
  96841. * @returns The cloned material.
  96842. */
  96843. BackgroundMaterial.prototype.clone = function (name) {
  96844. var _this = this;
  96845. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96846. };
  96847. /**
  96848. * Serializes the current material to its JSON representation.
  96849. * @returns The JSON representation.
  96850. */
  96851. BackgroundMaterial.prototype.serialize = function () {
  96852. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96853. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96854. return serializationObject;
  96855. };
  96856. /**
  96857. * Gets the class name of the material
  96858. * @returns "BackgroundMaterial"
  96859. */
  96860. BackgroundMaterial.prototype.getClassName = function () {
  96861. return "BackgroundMaterial";
  96862. };
  96863. /**
  96864. * Parse a JSON input to create back a background material.
  96865. * @param source The JSON data to parse
  96866. * @param scene The scene to create the parsed material in
  96867. * @param rootUrl The root url of the assets the material depends upon
  96868. * @returns the instantiated BackgroundMaterial.
  96869. */
  96870. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96871. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96872. };
  96873. /**
  96874. * Standard reflectance value at parallel view angle.
  96875. */
  96876. BackgroundMaterial.StandardReflectance0 = 0.05;
  96877. /**
  96878. * Standard reflectance value at grazing angle.
  96879. */
  96880. BackgroundMaterial.StandardReflectance90 = 0.5;
  96881. __decorate([
  96882. BABYLON.serializeAsColor3()
  96883. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96884. __decorate([
  96885. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96886. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96887. __decorate([
  96888. BABYLON.serializeAsColor3()
  96889. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96890. __decorate([
  96891. BABYLON.serialize()
  96892. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96893. __decorate([
  96894. BABYLON.serialize()
  96895. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96896. __decorate([
  96897. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96898. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96899. __decorate([
  96900. BABYLON.serializeAsTexture()
  96901. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96902. __decorate([
  96903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96904. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96905. __decorate([
  96906. BABYLON.serialize()
  96907. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96908. __decorate([
  96909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96910. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96911. __decorate([
  96912. BABYLON.serializeAsTexture()
  96913. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96914. __decorate([
  96915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96916. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96917. __decorate([
  96918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96919. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96920. __decorate([
  96921. BABYLON.serialize()
  96922. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96923. __decorate([
  96924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96925. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96926. __decorate([
  96927. BABYLON.serializeAsVector3()
  96928. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96929. __decorate([
  96930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96931. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96932. __decorate([
  96933. BABYLON.serialize()
  96934. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96935. __decorate([
  96936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96937. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96938. __decorate([
  96939. BABYLON.serialize()
  96940. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96941. __decorate([
  96942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96943. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96944. __decorate([
  96945. BABYLON.serialize()
  96946. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96947. __decorate([
  96948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96949. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96950. __decorate([
  96951. BABYLON.serialize()
  96952. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96953. __decorate([
  96954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96955. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96956. __decorate([
  96957. BABYLON.serialize()
  96958. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96959. __decorate([
  96960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96961. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96962. __decorate([
  96963. BABYLON.serialize()
  96964. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96965. __decorate([
  96966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96967. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96968. __decorate([
  96969. BABYLON.serialize()
  96970. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96971. __decorate([
  96972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96973. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96974. __decorate([
  96975. BABYLON.serialize()
  96976. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96977. __decorate([
  96978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96979. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96980. __decorate([
  96981. BABYLON.serialize()
  96982. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96983. __decorate([
  96984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96985. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96986. __decorate([
  96987. BABYLON.serializeAsImageProcessingConfiguration()
  96988. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96989. return BackgroundMaterial;
  96990. }(BABYLON.PushMaterial));
  96991. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96992. })(BABYLON || (BABYLON = {}));
  96993. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96994. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96995. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96996. s = arguments[i];
  96997. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96998. t[p] = s[p];
  96999. }
  97000. return t;
  97001. };
  97002. var BABYLON;
  97003. (function (BABYLON) {
  97004. /**
  97005. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97006. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97007. * It also helps with the default setup of your imageProcessing configuration.
  97008. */
  97009. var EnvironmentHelper = /** @class */ (function () {
  97010. /**
  97011. * constructor
  97012. * @param options
  97013. * @param scene The scene to add the material to
  97014. */
  97015. function EnvironmentHelper(options, scene) {
  97016. var _this = this;
  97017. this._errorHandler = function (message, exception) {
  97018. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97019. };
  97020. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97021. this._scene = scene;
  97022. this.onErrorObservable = new BABYLON.Observable();
  97023. this._setupBackground();
  97024. this._setupImageProcessing();
  97025. }
  97026. /**
  97027. * Creates the default options for the helper.
  97028. */
  97029. EnvironmentHelper._getDefaultOptions = function () {
  97030. return {
  97031. createGround: true,
  97032. groundSize: 15,
  97033. groundTexture: this._groundTextureCDNUrl,
  97034. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97035. groundOpacity: 0.9,
  97036. enableGroundShadow: true,
  97037. groundShadowLevel: 0.5,
  97038. enableGroundMirror: false,
  97039. groundMirrorSizeRatio: 0.3,
  97040. groundMirrorBlurKernel: 64,
  97041. groundMirrorAmount: 1,
  97042. groundMirrorFresnelWeight: 1,
  97043. groundMirrorFallOffDistance: 0,
  97044. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97045. groundYBias: 0.00001,
  97046. createSkybox: true,
  97047. skyboxSize: 20,
  97048. skyboxTexture: this._skyboxTextureCDNUrl,
  97049. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97050. backgroundYRotation: 0,
  97051. sizeAuto: true,
  97052. rootPosition: BABYLON.Vector3.Zero(),
  97053. setupImageProcessing: true,
  97054. environmentTexture: this._environmentTextureCDNUrl,
  97055. cameraExposure: 0.8,
  97056. cameraContrast: 1.2,
  97057. toneMappingEnabled: true,
  97058. };
  97059. };
  97060. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97061. /**
  97062. * Gets the root mesh created by the helper.
  97063. */
  97064. get: function () {
  97065. return this._rootMesh;
  97066. },
  97067. enumerable: true,
  97068. configurable: true
  97069. });
  97070. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97071. /**
  97072. * Gets the skybox created by the helper.
  97073. */
  97074. get: function () {
  97075. return this._skybox;
  97076. },
  97077. enumerable: true,
  97078. configurable: true
  97079. });
  97080. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97081. /**
  97082. * Gets the skybox texture created by the helper.
  97083. */
  97084. get: function () {
  97085. return this._skyboxTexture;
  97086. },
  97087. enumerable: true,
  97088. configurable: true
  97089. });
  97090. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97091. /**
  97092. * Gets the skybox material created by the helper.
  97093. */
  97094. get: function () {
  97095. return this._skyboxMaterial;
  97096. },
  97097. enumerable: true,
  97098. configurable: true
  97099. });
  97100. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97101. /**
  97102. * Gets the ground mesh created by the helper.
  97103. */
  97104. get: function () {
  97105. return this._ground;
  97106. },
  97107. enumerable: true,
  97108. configurable: true
  97109. });
  97110. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97111. /**
  97112. * Gets the ground texture created by the helper.
  97113. */
  97114. get: function () {
  97115. return this._groundTexture;
  97116. },
  97117. enumerable: true,
  97118. configurable: true
  97119. });
  97120. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97121. /**
  97122. * Gets the ground mirror created by the helper.
  97123. */
  97124. get: function () {
  97125. return this._groundMirror;
  97126. },
  97127. enumerable: true,
  97128. configurable: true
  97129. });
  97130. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97131. /**
  97132. * Gets the ground mirror render list to helps pushing the meshes
  97133. * you wish in the ground reflection.
  97134. */
  97135. get: function () {
  97136. if (this._groundMirror) {
  97137. return this._groundMirror.renderList;
  97138. }
  97139. return null;
  97140. },
  97141. enumerable: true,
  97142. configurable: true
  97143. });
  97144. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97145. /**
  97146. * Gets the ground material created by the helper.
  97147. */
  97148. get: function () {
  97149. return this._groundMaterial;
  97150. },
  97151. enumerable: true,
  97152. configurable: true
  97153. });
  97154. /**
  97155. * Updates the background according to the new options
  97156. * @param options
  97157. */
  97158. EnvironmentHelper.prototype.updateOptions = function (options) {
  97159. var newOptions = __assign({}, this._options, options);
  97160. if (this._ground && !newOptions.createGround) {
  97161. this._ground.dispose();
  97162. this._ground = null;
  97163. }
  97164. if (this._groundMaterial && !newOptions.createGround) {
  97165. this._groundMaterial.dispose();
  97166. this._groundMaterial = null;
  97167. }
  97168. if (this._groundTexture) {
  97169. if (this._options.groundTexture != newOptions.groundTexture) {
  97170. this._groundTexture.dispose();
  97171. this._groundTexture = null;
  97172. }
  97173. }
  97174. if (this._skybox && !newOptions.createSkybox) {
  97175. this._skybox.dispose();
  97176. this._skybox = null;
  97177. }
  97178. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97179. this._skyboxMaterial.dispose();
  97180. this._skyboxMaterial = null;
  97181. }
  97182. if (this._skyboxTexture) {
  97183. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97184. this._skyboxTexture.dispose();
  97185. this._skyboxTexture = null;
  97186. }
  97187. }
  97188. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97189. this._groundMirror.dispose();
  97190. this._groundMirror = null;
  97191. }
  97192. if (this._scene.environmentTexture) {
  97193. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97194. this._scene.environmentTexture.dispose();
  97195. }
  97196. }
  97197. this._options = newOptions;
  97198. this._setupBackground();
  97199. this._setupImageProcessing();
  97200. };
  97201. /**
  97202. * Sets the primary color of all the available elements.
  97203. * @param color the main color to affect to the ground and the background
  97204. */
  97205. EnvironmentHelper.prototype.setMainColor = function (color) {
  97206. if (this.groundMaterial) {
  97207. this.groundMaterial.primaryColor = color;
  97208. }
  97209. if (this.skyboxMaterial) {
  97210. this.skyboxMaterial.primaryColor = color;
  97211. }
  97212. if (this.groundMirror) {
  97213. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97214. }
  97215. };
  97216. /**
  97217. * Setup the image processing according to the specified options.
  97218. */
  97219. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97220. if (this._options.setupImageProcessing) {
  97221. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97222. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97223. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97224. this._setupEnvironmentTexture();
  97225. }
  97226. };
  97227. /**
  97228. * Setup the environment texture according to the specified options.
  97229. */
  97230. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97231. if (this._scene.environmentTexture) {
  97232. return;
  97233. }
  97234. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97235. this._scene.environmentTexture = this._options.environmentTexture;
  97236. return;
  97237. }
  97238. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97239. this._scene.environmentTexture = environmentTexture;
  97240. };
  97241. /**
  97242. * Setup the background according to the specified options.
  97243. */
  97244. EnvironmentHelper.prototype._setupBackground = function () {
  97245. if (!this._rootMesh) {
  97246. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97247. }
  97248. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97249. var sceneSize = this._getSceneSize();
  97250. if (this._options.createGround) {
  97251. this._setupGround(sceneSize);
  97252. this._setupGroundMaterial();
  97253. this._setupGroundDiffuseTexture();
  97254. if (this._options.enableGroundMirror) {
  97255. this._setupGroundMirrorTexture(sceneSize);
  97256. }
  97257. this._setupMirrorInGroundMaterial();
  97258. }
  97259. if (this._options.createSkybox) {
  97260. this._setupSkybox(sceneSize);
  97261. this._setupSkyboxMaterial();
  97262. this._setupSkyboxReflectionTexture();
  97263. }
  97264. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97265. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97266. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97267. };
  97268. /**
  97269. * Get the scene sizes according to the setup.
  97270. */
  97271. EnvironmentHelper.prototype._getSceneSize = function () {
  97272. var _this = this;
  97273. var groundSize = this._options.groundSize;
  97274. var skyboxSize = this._options.skyboxSize;
  97275. var rootPosition = this._options.rootPosition;
  97276. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97277. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97278. }
  97279. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97280. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97281. });
  97282. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97283. if (this._options.sizeAuto) {
  97284. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97285. this._scene.activeCamera.upperRadiusLimit) {
  97286. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97287. skyboxSize = groundSize;
  97288. }
  97289. var sceneDiagonalLenght = sceneDiagonal.length();
  97290. if (sceneDiagonalLenght > groundSize) {
  97291. groundSize = sceneDiagonalLenght * 2;
  97292. skyboxSize = groundSize;
  97293. }
  97294. // 10 % bigger.
  97295. groundSize *= 1.1;
  97296. skyboxSize *= 1.5;
  97297. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97298. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97299. }
  97300. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97301. };
  97302. /**
  97303. * Setup the ground according to the specified options.
  97304. */
  97305. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97306. var _this = this;
  97307. if (!this._ground) {
  97308. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97309. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97310. this._ground.parent = this._rootMesh;
  97311. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97312. }
  97313. this._ground.receiveShadows = this._options.enableGroundShadow;
  97314. };
  97315. /**
  97316. * Setup the ground material according to the specified options.
  97317. */
  97318. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97319. if (!this._groundMaterial) {
  97320. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97321. }
  97322. this._groundMaterial.alpha = this._options.groundOpacity;
  97323. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97324. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97325. this._groundMaterial.primaryColor = this._options.groundColor;
  97326. this._groundMaterial.useRGBColor = false;
  97327. this._groundMaterial.enableNoise = true;
  97328. if (this._ground) {
  97329. this._ground.material = this._groundMaterial;
  97330. }
  97331. };
  97332. /**
  97333. * Setup the ground diffuse texture according to the specified options.
  97334. */
  97335. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97336. if (!this._groundMaterial) {
  97337. return;
  97338. }
  97339. if (this._groundTexture) {
  97340. return;
  97341. }
  97342. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97343. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97344. return;
  97345. }
  97346. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97347. diffuseTexture.gammaSpace = false;
  97348. diffuseTexture.hasAlpha = true;
  97349. this._groundMaterial.diffuseTexture = diffuseTexture;
  97350. };
  97351. /**
  97352. * Setup the ground mirror texture according to the specified options.
  97353. */
  97354. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97355. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97356. if (!this._groundMirror) {
  97357. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97358. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97359. this._groundMirror.anisotropicFilteringLevel = 1;
  97360. this._groundMirror.wrapU = wrapping;
  97361. this._groundMirror.wrapV = wrapping;
  97362. this._groundMirror.gammaSpace = false;
  97363. if (this._groundMirror.renderList) {
  97364. for (var i = 0; i < this._scene.meshes.length; i++) {
  97365. var mesh = this._scene.meshes[i];
  97366. if (mesh !== this._ground &&
  97367. mesh !== this._skybox &&
  97368. mesh !== this._rootMesh) {
  97369. this._groundMirror.renderList.push(mesh);
  97370. }
  97371. }
  97372. }
  97373. }
  97374. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97375. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97376. };
  97377. /**
  97378. * Setup the ground to receive the mirror texture.
  97379. */
  97380. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97381. if (this._groundMaterial) {
  97382. this._groundMaterial.reflectionTexture = this._groundMirror;
  97383. this._groundMaterial.reflectionFresnel = true;
  97384. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97385. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97386. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97387. }
  97388. };
  97389. /**
  97390. * Setup the skybox according to the specified options.
  97391. */
  97392. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97393. var _this = this;
  97394. if (!this._skybox) {
  97395. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97396. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97397. }
  97398. this._skybox.parent = this._rootMesh;
  97399. };
  97400. /**
  97401. * Setup the skybox material according to the specified options.
  97402. */
  97403. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97404. if (!this._skybox) {
  97405. return;
  97406. }
  97407. if (!this._skyboxMaterial) {
  97408. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97409. }
  97410. this._skyboxMaterial.useRGBColor = false;
  97411. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97412. this._skyboxMaterial.enableNoise = true;
  97413. this._skybox.material = this._skyboxMaterial;
  97414. };
  97415. /**
  97416. * Setup the skybox reflection texture according to the specified options.
  97417. */
  97418. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97419. if (!this._skyboxMaterial) {
  97420. return;
  97421. }
  97422. if (this._skyboxTexture) {
  97423. return;
  97424. }
  97425. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97426. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97427. return;
  97428. }
  97429. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97430. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97431. this._skyboxTexture.gammaSpace = false;
  97432. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97433. };
  97434. /**
  97435. * Dispose all the elements created by the Helper.
  97436. */
  97437. EnvironmentHelper.prototype.dispose = function () {
  97438. if (this._groundMaterial) {
  97439. this._groundMaterial.dispose(true, true);
  97440. }
  97441. if (this._skyboxMaterial) {
  97442. this._skyboxMaterial.dispose(true, true);
  97443. }
  97444. this._rootMesh.dispose(false);
  97445. };
  97446. /**
  97447. * Default ground texture URL.
  97448. */
  97449. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97450. /**
  97451. * Default skybox texture URL.
  97452. */
  97453. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97454. /**
  97455. * Default environment texture URL.
  97456. */
  97457. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97458. return EnvironmentHelper;
  97459. }());
  97460. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97461. })(BABYLON || (BABYLON = {}));
  97462. //# sourceMappingURL=babylon.environmentHelper.js.map
  97463. var BABYLON;
  97464. (function (BABYLON) {
  97465. /**
  97466. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97467. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97468. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97469. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97470. */
  97471. var VideoDome = /** @class */ (function (_super) {
  97472. __extends(VideoDome, _super);
  97473. /**
  97474. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97475. * @param name Element's name, child elements will append suffixes for their own names.
  97476. * @param urlsOrVideo
  97477. * @param options An object containing optional or exposed sub element properties:
  97478. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97479. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97480. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97481. * @param options **loop=true** Automatically loop video on end.
  97482. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97483. */
  97484. function VideoDome(name, urlsOrVideo, options, scene) {
  97485. var _this = _super.call(this, name, scene) || this;
  97486. // set defaults and manage values
  97487. name = name || "videoDome";
  97488. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97489. options.clickToPlay = Boolean(options.clickToPlay);
  97490. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97491. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97492. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97493. // create
  97494. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97495. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97496. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97497. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97498. flat: false,
  97499. radius: options.size,
  97500. subdivisions: options.resolution,
  97501. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97502. }, scene);
  97503. // configure material
  97504. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97505. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97506. material.reflectionTexture = _this._videoTexture;
  97507. material.useEquirectangularFOV = true;
  97508. material.fovMultiplier = 1.0;
  97509. // configure mesh
  97510. _this._mesh.material = material;
  97511. _this._mesh.parent = _this;
  97512. // optional configuration
  97513. if (options.clickToPlay) {
  97514. scene.onPointerUp = function () {
  97515. _this._videoTexture.video.play();
  97516. };
  97517. }
  97518. return _this;
  97519. }
  97520. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97521. /**
  97522. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97523. * Also see the options.resolution property.
  97524. */
  97525. get: function () {
  97526. return this._material.fovMultiplier;
  97527. },
  97528. set: function (value) {
  97529. this._material.fovMultiplier = value;
  97530. },
  97531. enumerable: true,
  97532. configurable: true
  97533. });
  97534. /**
  97535. * Releases resources associated with this node.
  97536. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97537. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97538. */
  97539. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97540. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97541. this._videoTexture.dispose();
  97542. this._mesh.dispose();
  97543. this._material.dispose();
  97544. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97545. };
  97546. return VideoDome;
  97547. }(BABYLON.Node));
  97548. BABYLON.VideoDome = VideoDome;
  97549. })(BABYLON || (BABYLON = {}));
  97550. //# sourceMappingURL=babylon.videoDome.js.map
  97551. 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\nvPositionUVW=positionUpdated;\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\nvPositionUVW=positionUpdated;\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(GEOMETRYAA)\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#ifdef GEOMETRYAA\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#include<bumpFragment>\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 GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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;\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(reflectionCoords,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*=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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\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}","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}","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;\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;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\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\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\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}","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}","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\nvPositionUVW=position;\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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*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,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"};
  97552. 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","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","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}","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};\n#endif\n#ifdef 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;\n#endif\n#ifdef 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 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=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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\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\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\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","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","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}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef 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#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(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#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if 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 vec3 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 vec3 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 vec3 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#ifdef USEPHYSICALLIGHTFALLOFF\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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*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*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,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*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*attenuation;\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}","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};","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","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};"};